File size: 1,636 Bytes
a2b2aac |
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 71 72 |
import { resolve, dirname as _dirname } from 'path'
import _fs, { existsSync, readFileSync } from '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 = 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 = existsSync(this.file) ? JSON.parse(readFileSync(this.file)) : {}
} catch (e) {
this.logger.error(e)
return this._data = {}
}
}
async _save() {
let dirname = _dirname(this.file)
if (!existsSync(dirname)) await fs.mkdir(dirname, { recursive: true })
await fs.writeFile(this.file, JSON.stringify(this._data, ...this._jsonargs))
return this.file
}
}
export default Database
|