Last active
February 20, 2021 01:24
-
-
Save jctaoo/46c333dfed91ea2feabee2d479bc43a4 to your computer and use it in GitHub Desktop.
Type-safed simple store use in electron.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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