Store/store.ts

46 lines
1.1 KiB
TypeScript

const REFRESH_EVENT = "bm:refresh-store";
export class BearMetalStore {
private store: Record<string, string | number | boolean> = {};
private storePath: string;
public readonly EVENT_NAME: string;
constructor(storePath?: string) {
this.storePath = storePath || Deno.env.get("BEAR_METAL_STORE_PATH") ||
"./BearMetal/store.json";
this.EVENT_NAME = REFRESH_EVENT + this.storePath;
this.readIn();
globalThis.addEventListener(this.EVENT_NAME, this.readIn);
}
public get(key: string): string | number | boolean {
return this.store[key];
}
public set(key: string, value: string | number | boolean): void {
this.store[key] = value;
this.writeOut();
}
public delete(key: string): void {
delete this.store[key];
this.writeOut();
}
private readIn() {
this.store = JSON.parse(Deno.readTextFileSync(this.storePath));
}
private writeOut() {
Deno.writeTextFileSync(this.storePath, JSON.stringify(this.store));
globalThis.dispatchEvent(new CustomEvent(this.EVENT_NAME));
}
[Symbol.dispose]() {
this.writeOut();
globalThis.removeEventListener(this.EVENT_NAME, this.readIn);
}
}