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",
"version": "1.0.0",
"version": "1.0.3",
"author": "mifi (Mike Fitzpatrick)",
"license": "MIT",
"scripts": {

View File

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