-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage.ts
38 lines (33 loc) · 835 Bytes
/
storage.ts
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
import fs from 'fs/promises';
async function exists(filename: string) {
try {
await fs.access(filename);
return true;
} catch (_) {
return false;
}
}
export interface Storage {
get: (key: string) => Promise<any>;
set: (key: string, value: any) => Promise<void>;
}
export function createFileStorage(filename: string): Storage {
return {
get: async (key: string) => {
let file;
try {
file = await fs.readFile(filename);
} catch (_) {
return null;
}
return JSON.parse(String(file))[key] ?? null;
},
set: async (key: string, value: any) => {
const obj = (await exists(filename))
? JSON.parse(String(await fs.readFile(filename)))
: {};
obj[key] = value;
await fs.writeFile(filename, JSON.stringify(obj));
},
};
}