forked from ariffb25/stikerinbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
71 lines (59 loc) · 1.57 KB
/
database.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
const path = require('path')
const _fs = require('fs')
const { promises: fs } = _fs
class Database {
/**
* Create new Database
* @param {String} filepath Path to specified json database
* @param {...any} args JSON.stringify arguments
*/
constructor(filepath, ...args) {
this.file = path.resolve(filepath)
this.logger = console
this._load()
this._jsonargs = args
this._state = false
this._queue = []
this._interval = setInterval(async () => {
if (!this._state && this._queue && this._queue[0]) {
this._state = true
await this[this._queue.shift()]().catch(this.logger.error)
this._state = false
}
}, 1000)
}
get data() {
return this._data
}
set data(value) {
this._data = value
this.save()
}
/**
* Queue Load
*/
load() {
this._queue.push('_load')
}
/**
* Queue Save
*/
save() {
this._queue.push('_save')
}
_load() {
try {
return this._data = _fs.existsSync(this.file) ? JSON.parse(_fs.readFileSync(this.file)) : {}
} catch (e) {
this.logger.error(e)
return this._data = {}
}
}
async _save() {
let dirname = path.dirname(this.file)
if (!_fs.existsSync(dirname)) await fs.mkdir(dirname, { recursive: true })
await fs.writeFile(this.file, JSON.stringify(this._data, ...this._jsonargs))
return this.file
}
}
module.exports = Database