Last active
February 15, 2022 00:15
-
-
Save nobu-sh/619f9134a582f66c73bb97ecad28c8c1 to your computer and use it in GitHub Desktop.
Simple NodeJS JSON Database.
This file contains 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 { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' | |
import { dirname, resolve } from 'path' | |
export class Store<T extends Record<any, any>> { | |
protected readonly aPath: string | |
protected readonly data: T | |
constructor(path: string) { | |
this.aPath = resolve(__dirname, path) | |
if (!existsSync(this.aPath)) { | |
const directory = dirname(this.aPath) | |
mkdirSync(directory, { recursive: true }) | |
writeFileSync(this.aPath, JSON.stringify({})) | |
} | |
this.data = JSON.parse(readFileSync(this.aPath, 'utf8')) | |
} | |
public get<K extends keyof T>(key: K): T[K] { | |
return this.data[key] | |
} | |
public set<K extends keyof T>(key: K, value: T[K]): this { | |
this.data[key] = value | |
return this | |
} | |
public update<K extends keyof T>(key: K, update: Partial<T[K]>): this { | |
this.data[key] = { ...this.data[key], ...update } | |
return this | |
} | |
public delete<K extends keyof T>(key: K): this { | |
delete this.data[key] | |
return this | |
} | |
public keys<K extends keyof T>(): K[] { | |
return Object.keys(this.data) as K[] | |
} | |
public values<K extends keyof T>(): (T[K])[] { | |
return Object.values(this.data) | |
} | |
public entries<K extends keyof T>(): [K, T[K]][] { | |
return Object.entries(this.data) as [K, T[K]][] | |
} | |
public save(): this { | |
writeFileSync(this.aPath, JSON.stringify(this.data)) | |
return this | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment