2019-07-26 22:34:25 +02:00
|
|
|
import path from 'path';
|
2020-03-02 23:15:44 +01:00
|
|
|
import fs from 'fs-extra';
|
2020-04-10 05:02:19 +02:00
|
|
|
import { appPath } from '../../core/app-path';
|
2019-07-26 22:34:25 +02:00
|
|
|
|
|
|
|
export const enum StoreKeys {
|
|
|
|
'COOKIES' = 'cookies',
|
|
|
|
}
|
|
|
|
|
|
|
|
type Store = {
|
|
|
|
[key in StoreKeys]?: any;
|
|
|
|
};
|
|
|
|
|
|
|
|
interface IStoreOptions {
|
|
|
|
path: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
let store: Store = {};
|
|
|
|
let synced = false;
|
|
|
|
|
|
|
|
const options: IStoreOptions = {
|
2020-02-08 23:26:57 +01:00
|
|
|
path: path.resolve(appPath, 'store', 'store.json'),
|
2019-07-26 22:34:25 +02:00
|
|
|
};
|
|
|
|
const folder = path.dirname(options.path);
|
|
|
|
|
|
|
|
function initDir(): Promise<void> {
|
|
|
|
if (!fs.existsSync(folder)) {
|
2019-11-18 22:38:51 +01:00
|
|
|
return fs.promises.mkdir(folder, { recursive: true }).then(() => writeUnsave());
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
|
|
|
if (!fs.existsSync(options.path)) {
|
|
|
|
return writeUnsave();
|
|
|
|
}
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
|
|
|
|
function writeUnsave(): Promise<void> {
|
2019-11-18 22:38:51 +01:00
|
|
|
return fs.writeFile(options.path, JSON.stringify(store));
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function read(): Promise<void> {
|
2019-12-15 01:14:39 +01:00
|
|
|
return initDir().then(() =>
|
|
|
|
fs.readFile(options.path).then((buf: Buffer) => {
|
2019-07-26 22:34:25 +02:00
|
|
|
store = JSON.parse(buf.toString());
|
|
|
|
synced = true;
|
2019-12-15 01:14:39 +01:00
|
|
|
})
|
|
|
|
);
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function write(): Promise<void> {
|
2019-12-15 01:14:39 +01:00
|
|
|
return initDir().then(() =>
|
|
|
|
writeUnsave().then(() => {
|
2019-07-26 22:34:25 +02:00
|
|
|
synced = false;
|
2019-12-15 01:14:39 +01:00
|
|
|
})
|
|
|
|
);
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export function load(key: StoreKeys): Promise<any> {
|
|
|
|
if (synced) {
|
2019-12-15 01:14:39 +01:00
|
|
|
return Promise.resolve(store[key]);
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
2019-12-15 01:14:39 +01:00
|
|
|
return read().then(() => Promise.resolve(store[key]));
|
2019-07-26 22:34:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export function save(key: StoreKeys, data: any): Promise<void> {
|
|
|
|
store[key] = data;
|
|
|
|
return write();
|
|
|
|
}
|