-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDBInfoDriver.ts
More file actions
59 lines (52 loc) · 1.52 KB
/
DBInfoDriver.ts
File metadata and controls
59 lines (52 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { FileRepository } from "../../lib/repo/FileRepository";
import { typedKeys } from "../../lib/std/typedKeys";
import { Config } from "./ConfigRepository";
export class DBInfoDriver {
constructor(public readonly file: FileRepository<Config>) {}
async read(prefix: string): Promise<DBInfo> {
const values = await this.file;
const requireProp = (prop: keyof DBInfo) => {
const key = createKey(prefix, prop);
const value = values?.[key];
if (value === undefined) {
throw new Error(
`Config file "${this.file.filename}" is missing key "${key}"`
);
}
return value;
};
// prettier-ignore
return {
host: requireProp("host"),
port: parseInt(requireProp("port"), 10),
user: requireProp("user"),
password: requireProp("password"),
database: requireProp("database")
};
}
async update(changes: Record<string, DBInfo>) {
const values = (await this.file.read()) ?? {};
for (const [prefix, info] of Object.entries(changes)) {
for (const prop of typedKeys(info)) {
values[createKey(prefix, prop)] = `${info[prop]}`;
}
}
return this.file.write(values);
}
}
const propMap: Record<keyof DBInfo, string> = {
host: "ip",
port: "port",
user: "id",
password: "pw",
database: "db",
};
const createKey = (prefix: string, prop: keyof DBInfo) =>
`${prefix}_${propMap[prop]}`;
export type DBInfo = Readonly<{
host: string;
port: number;
user: string;
password: string;
database: string;
}>;