Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/lib/database.js
1126 views
1
const path = require('path')
2
const _fs = require('fs')
3
const { promises: fs } = _fs
4
5
class Database {
6
/**
7
* Create new Database
8
* @param {String} filepath Path to specified json database
9
* @param {...any} args JSON.stringify arguments
10
*/
11
constructor(filepath, ...args) {
12
this.file = path.resolve(filepath)
13
this.logger = console
14
15
this._load()
16
17
this._jsonargs = args
18
this._state = false
19
this._queue = []
20
this._interval = setInterval(async () => {
21
if (!this._state && this._queue && this._queue[0]) {
22
this._state = true
23
await this[this._queue.shift()]().catch(this.logger.error)
24
this._state = false
25
}
26
}, 1000)
27
28
}
29
30
get data() {
31
return this._data
32
}
33
34
set data(value) {
35
this._data = value
36
this.save()
37
}
38
39
/**
40
* Queue Load
41
*/
42
load() {
43
this._queue.push('_load')
44
}
45
46
/**
47
* Queue Save
48
*/
49
save() {
50
this._queue.push('_save')
51
}
52
53
_load() {
54
try {
55
return this._data = _fs.existsSync(this.file) ? JSON.parse(_fs.readFileSync(this.file)) : {}
56
} catch (e) {
57
this.logger.error(e)
58
return this._data = {}
59
}
60
}
61
62
async _save() {
63
let dirname = path.dirname(this.file)
64
if (!_fs.existsSync(dirname)) await fs.mkdir(dirname, { recursive: true })
65
await fs.writeFile(this.file, JSON.stringify(this._data, ...this._jsonargs))
66
return this.file
67
}
68
}
69
70
module.exports = Database
71
72
73