Skip to content

Instantly share code, notes, and snippets.

@jctaoo
Last active February 20, 2021 01:24
Show Gist options
  • Save jctaoo/46c333dfed91ea2feabee2d479bc43a4 to your computer and use it in GitHub Desktop.
Save jctaoo/46c333dfed91ea2feabee2d479bc43a4 to your computer and use it in GitHub Desktop.
Type-safed simple store use in electron.
import { app } from 'electron';
import * as path from 'path';
import * as fs from 'fs';
export default class SimpleStore<Model extends Object> {
static STORE_NAME = 'persistence.json';
private readonly storePath: string;
constructor() {
const appData = app.getPath('appData');
this.storePath = path.join(appData, SimpleStore.STORE_NAME);
}
public async set(newValue: Partial<Model>) {
const old = await this.readOrWriteEmpty();
const str = JSON.stringify({ ...old, ...newValue });
await fs.promises.writeFile(this.storePath, str);
}
public async get<Key extends keyof Model>(
key: Key
): Promise<Model[keyof Model] | undefined> {
if (await this.ensureFileExistsOrWriteEmpty()) {
const data = await this.readOrWriteEmpty();
return data[key];
}
return undefined;
}
private async ensureFileExistsOrWriteEmpty(): Promise<boolean> {
try {
await fs.promises.stat(this.storePath);
return true;
} catch {
this.writeEmpty().then();
return false;
}
}
private async readOrWriteEmpty(): Promise<Partial<Model>> {
const string = (await fs.promises.readFile(this.storePath)).toString();
try {
return JSON.parse(string) as Model;
} catch {
await this.writeEmpty();
return {};
}
}
private async writeEmpty() {
await fs.promises.writeFile(this.storePath, '{}');
return;
}
}
export default interface PersistenceModel {
openedProductionID: string[];
}
const store = new Store<PersistenceModel>();
await this.store.get('openedProduction'); // string[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment