RenaiApp/src/main/services/store.ts

73 lines
1.4 KiB
TypeScript
Raw Normal View History

import fs, { promises as fsp } from 'fs';
import path from 'path';
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 = {
path: path.resolve('store', 'store.json'),
};
const folder = path.dirname(options.path);
function initDir(): Promise<void> {
if (!fs.existsSync(folder)) {
return fsp.mkdir(folder).then(() => writeUnsave());
}
if (!fs.existsSync(options.path)) {
return writeUnsave();
}
return Promise.resolve();
}
function writeUnsave(): Promise<void> {
return fsp.writeFile(options.path, JSON.stringify(store));
}
function read(): Promise<void> {
return initDir().then(() => {
return fsp.readFile(options.path).then((buf: Buffer) => {
store = JSON.parse(buf.toString());
synced = true;
});
});
}
function write(): Promise<void> {
return initDir().then(() => {
return writeUnsave().then(() => {
synced = false;
});
});
}
function get(key: StoreKeys): any {
return store[key];
}
export function load(key: StoreKeys): Promise<any> {
if (synced) {
return Promise.resolve(get(key));
} else {
return read().then(() => {
return Promise.resolve(get(key));
});
}
}
export function save(key: StoreKeys, data: any): Promise<void> {
store[key] = data;
return write();
}