-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
50 lines (44 loc) · 875 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
45
46
47
48
49
50
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const fs = require('fs');
let db;
const DB_FILENAME = 'db.json';
const TEST_DB_FILENAME = 'test-db.json';
/**
* @param {boolean} [testMode] = false
* @returns {object} DB
*/
function initDb(testMode = false) {
const dbFilename = testMode ? TEST_DB_FILENAME : DB_FILENAME;
const isExists = fs.existsSync(dbFilename);
const adapter = new FileSync(dbFilename);
const _db = low(adapter);
if (!isExists) {
_db.defaults({
users: [],
tokens: [],
chats: [],
messages: []
}).write();
}
db = _db;
return db;
}
/**
* @returns {object} DB
*/
function getDb() {
return db;
}
/**
*
*/
function cleanTestDb() {
fs.existsSync(TEST_DB_FILENAME) && fs.unlinkSync(TEST_DB_FILENAME);
}
module.exports = {
initDb,
getDb,
cleanTestDb,
db
};