From c645597691ed324f13082ccd47c6c756e7f245fc Mon Sep 17 00:00:00 2001 From: mifi Date: Tue, 30 May 2023 17:44:00 -0400 Subject: [PATCH] Make singleton --- package.json | 2 +- src/index.ts | 28 +++++++++++++++++++++------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index f87cd00..fa27bd4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mifi/breakerbox-db", - "version": "1.0.0", + "version": "1.0.3", "author": "mifi (Mike Fitzpatrick)", "license": "MIT", "scripts": { diff --git a/src/index.ts b/src/index.ts index 57fdd3c..549b122 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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(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 }) {