-
Notifications
You must be signed in to change notification settings - Fork 6
/
db.js
44 lines (36 loc) · 915 Bytes
/
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
const fs = require("fs");
const path = require("path");
const DB_PATH = path.join(__dirname, "db.json");
const saveUsers = formattedDBUsers => {
fs.writeFileSync(
DB_PATH,
JSON.stringify(formattedDBUsers),
{ flag: "w" },
err => {
if (err) {
console.log("ERROR");
console.log(err);
} else {
console.log("ALL GOOD");
}
}
);
};
const getUsers = () => {
const rawDBUsers = fs.existsSync(DB_PATH) ? fs.readFileSync(DB_PATH) : `[]`;
return JSON.parse(rawDBUsers);
};
const getUser = index => getUsers()[index];
const getUsernames = DBUsers => DBUsers.map(DBUser => DBUser.name);
const getUsername = index => getUsers()[index].name;
const getIDs = () => getUsers().map(DBUser => DBUser.id);
const exists = () => fs.existsSync(DB_PATH);
module.exports = {
saveUsers,
getUsers,
getUser,
getUsernames,
getUsername,
getIDs,
exists
};