Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jajbshjahavahh
GitHub Repository: jajbshjahavahh/Gojo-Satoru
Path: blob/master/lib/database.js
2591 views
1
//═══════════════════════════════════════════════════════//
2
//If you want to recode, reupload
3
//or copy the codes/script,
4
//pls give credit
5
//no credit? i will take action immediately
6
//© 2022 Xeon Bot Inc. Cheems Bot MD
7
//Thank you to Lord Buddha, Family and Myself
8
//════════════════════════════//
9
const path = require('path')
10
const _fs = require('fs')
11
const { promises: fs } = _fs
12
13
class Database {
14
/**
15
* Create new Database
16
* @param {String} filepath Path to specified json database
17
* @param {...any} args JSON.stringify arguments
18
*/
19
constructor(filepath, ...args) {
20
this.file = path.resolve(filepath)
21
this.logger = console
22
23
this._load()
24
25
this._jsonargs = args
26
this._state = false
27
this._queue = []
28
this._interval = setInterval(async () => {
29
if (!this._state && this._queue && this._queue[0]) {
30
this._state = true
31
await this[this._queue.shift()]().catch(this.logger.error)
32
this._state = false
33
}
34
}, 1000)
35
36
}
37
38
get data() {
39
return this._data
40
}
41
42
set data(value) {
43
this._data = value
44
this.save()
45
}
46
47
/**
48
* Queue Load
49
*/
50
load() {
51
this._queue.push('_load')
52
}
53
54
/**
55
* Queue Save
56
*/
57
save() {
58
this._queue.push('_save')
59
}
60
61
_load() {
62
try {
63
return this._data = _fs.existsSync(this.file) ? JSON.parse(_fs.readFileSync(this.file)) : {}
64
} catch (e) {
65
this.logger.error(e)
66
return this._data = {}
67
}
68
}
69
70
async _save() {
71
let dirname = path.dirname(this.file)
72
if (!_fs.existsSync(dirname)) await fs.mkdir(dirname, { recursive: true })
73
await fs.writeFile(this.file, JSON.stringify(this._data, ...this._jsonargs))
74
return this.file
75
}
76
}
77
78
module.exports = Database
79
80
81