A Simple JSON Backed Database in Typescript
07 July 2022
Updated: 03 September 2023
Define the database
The database is defined as a class which has an in-memory store data
and a persist
method that allows for persisting the database to a file as well as content when an instance is created from an existing JSON file
The code for the database can be seen below:
1import { existsSync, readFileSync, writeFileSync } from 'fs'2
3export class Database<TData> {4 public data: TData5
6 constructor(private readonly dbPath: string, initial: TData) {7 this.data = this.load(initial)8 }9
10 public update = (data: Partial<TData>) =>11 (this.data = { ...this.data, ...data })12
13 public commit = () => this.persist(this.data)14
15 private persist = (data: TData) =>16 writeFileSync(this.dbPath, JSON.stringify(data))17
18 private read = (): TData =>19 JSON.parse(readFileSync(this.dbPath).toString()) as TData20
21 private load = (initial: TData): TData => {22 if (!existsSync(this.dbPath)) {23 this.persist(initial)24 }25
26 const current = this.read()27
28 return {29 ...initial,30 ...current,31 }32 }33}
Usage
The database can be used by creating an instance and modifying the data in it by using the update
method, and can be written to a file using the commit
method:
1import { Database } from './db'2
3interface User {4 name: string5 age: number6}7
8interface DB {9 users: User[]10}11
12const initial: DB = {13 users: [],14}15
16const db = new Database<DB>('./data.json', initial)17
18db.update({19 users: [20 {21 name: 'Test',22 age: 20,23 },24 ],25})26
27db.commit()
Functional Example
The above code is found in the below REPL as a runnable example: