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:

1
import { existsSync, readFileSync, writeFileSync } from 'fs'
2
3
export class Database<TData> {
4
public data: TData
5
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 TData
20
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:

1
import { Database } from './db'
2
3
interface User {
4
name: string
5
age: number
6
}
7
8
interface DB {
9
users: User[]
10
}
11
12
const initial: DB = {
13
users: [],
14
}
15
16
const db = new Database<DB>('./data.json', initial)
17
18
db.update({
19
users: [
20
{
21
name: 'Test',
22
age: 20,
23
},
24
],
25
})
26
27
db.commit()

Functional Example

The above code is found in the below REPL as a runnable example: