1 | import { isAbsolute, join } from 'path';
|
2 | import { cwd } from 'process';
|
3 | import { get, set } from 'lodash';
|
4 | import { pathExistsSync, readJSONSync, writeJSON } from 'fs-extra';
|
5 | import DataLoader from 'dataloader';
|
6 |
|
7 | class FileCache {
|
8 | constructor({ path }) {
|
9 | this.absolutePath = isAbsolute(path) ? path : join(cwd(), path);
|
10 | this.json = pathExistsSync(this.absolutePath) ? readJSONSync(this.absolutePath) : {};
|
11 | this.writeDataLoader = new DataLoader(async (keys) => {
|
12 | await writeJSON(this.absolutePath, this.json);
|
13 | return keys;
|
14 | });
|
15 | }
|
16 | async get(name) {
|
17 | return get(this.json, name);
|
18 | }
|
19 | async set(name, value) {
|
20 | set(this.json, name, value);
|
21 | this.writeDataLoader.load({});
|
22 | }
|
23 | async delete(name) {
|
24 | this.set(name, undefined);
|
25 | }
|
26 | }
|
27 |
|
28 | export default FileCache;
|
29 |
|