-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
50 lines (43 loc) · 1.06 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
import { Low, JSONFile } from 'lowdb';
type UserDb = {
users: User[];
};
export type User = {
id: number;
email: string;
phone: string;
skipMail?: boolean;
};
export default class DbUtil {
db: Low<UserDb>;
constructor() {
this.db = new Low<UserDb>(new JSONFile('db.json'));
}
async fetchEmails(): Promise<string[]> {
await this.db.read();
const users = this.db.data.users;
return users.map((r) => r.email);
}
async fetchUsers(): Promise<User[]> {
await this.db.read();
return this.db.data.users;
}
async addUser(email: string, phone: string) {
await this.db.read();
const nextId = this.db.data.users.length > 0 ? this.db.data.users[this.db.data.users.length - 1].id + 1 : 1;
this.db.data.users.push({ id: nextId, email, phone });
await this.db.write();
}
async removeUser(email: string) {
await this.db.read();
const users = this.db.data.users;
const index = users.findIndex((user) => user.email === email);
if (index > -1) {
users.splice(index, 1);
}
await this.db.write();
}
async save() {
await this.db.write();
}
}