| 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 = 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 | get data() { |
| 30 | return this._data |
| 31 | } |
| 32 | |
| 33 | set data(value) { |
| 34 | this._data = value |
| 35 | this.save() |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Queue Load |
| 40 | */ |
| 41 | load() { |
| 42 | this._queue.push('_load') |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Queue Save |
| 47 | */ |
| 48 | save() { |
| 49 | this._queue.push('_save') |
| 50 | } |
| 51 | |
| 52 | _load() { |
| 53 | try { |
| 54 | return (this._data = existsSync(this.file) ? JSON.parse(readFileSync(this.file)) : {}) |
| 55 | } catch (e) { |
| 56 | this.logger.error(e) |
| 57 | return (this._data = {}) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | async _save() { |
| 62 | let dirname = _dirname(this.file) |
nothing calls this directly
no outgoing calls
no test coverage detected