-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.js
75 lines (60 loc) · 1.53 KB
/
db.js
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
import { DateTime } from 'luxon';
import { readFile, writeFile } from 'node:fs/promises';
const maxComments = 5;
let dbPromise;
let dbOpen = false;
export async function openDatabase({ dbFile }) {
if (dbOpen) {
throw new Error('Database is already open');
}
dbOpen = true;
try {
const dbContents = await readFile(dbFile, 'utf8');
const dbData = JSON.parse(dbContents);
dbPromise = Promise.resolve({ file: dbFile, data: dbData });
} catch (err) {
if (err.code === 'ENOENT') {
dbPromise = Promise.resolve({
file: dbFile,
data: createBlankDatabase()
});
return;
}
throw err;
}
}
function createBlankDatabase() {
return {
comments: []
};
}
export async function createComment({ name, text }) {
const db = await dbPromise;
const comment = { name, text, date: DateTime.now() };
db.data.comments.push(serializeComment(comment));
if (db.data.comments.length > maxComments) {
db.data.comments.splice(0, db.data.comments.length - maxComments);
}
await saveDatabase();
return comment;
}
export async function getComments() {
const db = await dbPromise;
return db.data.comments.map(comment => deserializeComment(comment));
}
function deserializeComment({ date, ...rest }) {
return {
...rest,
date: DateTime.fromISO(date)
};
}
function serializeComment({ date, ...rest }) {
return {
...rest,
date: date.toISO()
};
}
async function saveDatabase() {
const db = await dbPromise;
await writeFile(db.file, JSON.stringify(db.data), 'utf8');
}