-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
73 lines (64 loc) · 1.61 KB
/
db.ts
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
import { readJson, writeJson, exists } from "https://deno.land/std@v0.51.0/fs/mod.ts";
const DB_URL = "./db.json"
const initialize_db = async () => {
await writeJson(DB_URL, { users: [] })
}
const getData = async (): Promise<object> => {
if(!await exists(DB_URL)) {
await initialize_db()
}
return await readJson(DB_URL) as object
};
const writeData = async (data: any): Promise<void> => {
await writeJson(DB_URL, data)
};
export const addUser = async (user: any) => {
const db: any = await getData();
db["users"].push(user);
writeData(db);
};
export const addPages = async (username: string, pages: Array<object>) => {
const db: any = await getData();
db["users"].forEach((user: any) => {
if (user.username === username) {
pages.forEach(p => {
if (unique(user["pages"], p)) {
user["pages"].push(p);
}
});
return;
}
});
writeData(db);
};
export const setPages = async (username: string, pages: Array<object>) => {
const db: any = await getData();
db["users"].forEach((user: any) => {
if (user.username === username) {
user["pages"] = pages;
return;
}
});
writeData(db);
};
const unique = (arr1: Array<any>, obj: any) => {
let unique = true;
arr1.forEach(t => {
if (t.date === obj.date && t.content === obj.content) {
unique = false;
return;
}
});
return unique;
};
export const getUser = async (username: string) => {
const db: any = await getData();
let user = null;
db["users"].forEach((u: any) => {
if (u.username === username) {
user = u;
return;
}
});
return user;
};