Make singleton

This commit is contained in:
2023-05-30 17:44:00 -04:00
parent a9bbb934c1
commit c645597691
2 changed files with 22 additions and 8 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@mifi/breakerbox-db", "name": "@mifi/breakerbox-db",
"version": "1.0.0", "version": "1.0.3",
"author": "mifi (Mike Fitzpatrick)", "author": "mifi (Mike Fitzpatrick)",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {

View File

@@ -8,15 +8,22 @@ import { Fuses, Panel } from './types/Panel';
import { ValidValues } from './types/ValidValues'; import { ValidValues } from './types/ValidValues';
import { SettingsMeta } from './types/SettingsMeta'; import { SettingsMeta } from './types/SettingsMeta';
interface BreakerboxProps {
filename?: string;
path?: string;
defaultStore?: Panel;
storageType: 'json' | 'yaml';
}
export class Breakerbox { export class Breakerbox {
private static instance: Breakerbox;
protected db; protected db;
public static defaultStore = { fuses: {} as Fuses } as Panel; public static defaultStore = { fuses: {} as Fuses } as Panel;
constructor( constructor(
filename = 'settings.json', filename: BreakerboxProps['filename'] = 'settings.json',
path = fileURLToPath(import.meta.url), path: BreakerboxProps['path'] = fileURLToPath(import.meta.url),
defaultStore = Breakerbox.defaultStore, defaultStore: BreakerboxProps['defaultStore'] = Breakerbox.defaultStore,
storageType: 'json' | 'yaml' = 'json', storageType: BreakerboxProps['storageType'] = 'json',
) { ) {
const __dirname = dirname(path); const __dirname = dirname(path);
const file = join(__dirname, filename); const file = join(__dirname, filename);
@@ -39,18 +46,25 @@ export class Breakerbox {
return this.db.data.fuses; return this.db.data.fuses;
} }
public getValue(key: string, defaultValue?: ValidValues, insert = false) { public static getInstance(props = {} as BreakerboxProps) {
if (!Breakerbox.instance) {
Breakerbox.instance = new Breakerbox(props.filename, props.path, props.defaultStore, props.storageType);
}
return Breakerbox.instance;
}
public getValue<T = ValidValues>(key: string, defaultValue?: T, insert = false) {
const fuse = this.get(key); const fuse = this.get(key);
if (fuse) { if (fuse) {
return fuse.value; return fuse.value as T;
} }
if (insert && defaultValue) { if (insert && defaultValue) {
this.set(key, defaultValue); this.set(key, defaultValue);
} }
return defaultValue; return defaultValue as T;
} }
public async set(key: string, value: ValidValues, meta = { type: typeof value }) { public async set(key: string, value: ValidValues, meta = { type: typeof value }) {