blob: 867e3c97e68d216d2b2f84f3ba58d490102eb7a4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
import { writeFile, readFile } from "fs";
import { promisify } from "util";
import { DatabaseInterface } from "./database.model";
import { Context } from "./context.model";
import { last } from "./util";
const splitPath = (path: string): string[] => path.split("/").filter(k => k);
const write = promisify(writeFile);
const read = promisify(readFile);
export const DB_CACHE_PATH = `${__dirname}/db.json`;
/**
* Implementation of NoSQL DB that uses paths and objects.
*
* Uses a plain object as a buffer and reads/writes to a
* plain JSON file. A better implementation could be backed
* by somethig a little nicer and not hold the buffer
* in memory
*/
export class Database implements DatabaseInterface {
private buff: any = {};
constructor(private ctx: Context = { logger: console.log }) {}
async init(): Promise<void> {
try {
const buff = await read(DB_CACHE_PATH);
this.buff = JSON.parse(buff.toString());
} catch (e) {
this.ctx.logger("Failed to init database, using empty object");
this.ctx.logger(e);
}
}
// this currently runs synchronously,
// but only because we hold the entire DB in memory
// (which obviously becomes a bad idea at some point)
async read(path: string): Promise<Object> {
const pathParts = splitPath(path);
return this.resolve(pathParts);
}
async write(path: string, toWrite: Object): Promise<void> {
const pathParts = splitPath(path);
const writeTo = this.resolve(pathParts, false, 1);
writeTo[last(pathParts)] = toWrite;
await this.serialize();
}
async flush(): Promise<void> {
this.buff = {};
await this.serialize();
}
toString() {
return JSON.stringify(this.buff);
}
private resolve(
pathParts: string[],
isRead: boolean = true,
level: number = 0
): any {
// start at the root of our buffer
let lastNode = this.buff;
let node;
for (let i = 0; i < pathParts.length - level; i++) {
const part: string = pathParts[i];
// handle null node
if (!lastNode[part]) {
// if we're reading from the object
// we want to stop as soon
// as we hit a null node
if (isRead) {
return null;
}
// but if we're writing and the node is missing,
// we should make it and continue
else {
lastNode[part] = {};
}
}
// traverse to the next node
node = lastNode[part];
lastNode = node;
}
return node;
}
private serialize(): Promise<void> {
return write(DB_CACHE_PATH, this.toString());
}
}
|