database.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {resolve, dirname as _dirname} from 'path';
  2. import _fs, {existsSync, readFileSync} from 'fs';
  3. const {promises: fs} = _fs;
  4. class Database {
  5. /**
  6. * Create new Database
  7. * @param {String} filepath Path to specified json database
  8. * @param {...any} args JSON.stringify arguments
  9. */
  10. constructor(filepath, ...args) {
  11. this.file = resolve(filepath);
  12. this.logger = console;
  13. this._load();
  14. this._jsonargs = args;
  15. this._state = false;
  16. this._queue = [];
  17. this._interval = setInterval(async () => {
  18. if (!this._state && this._queue && this._queue[0]) {
  19. this._state = true;
  20. await this[this._queue.shift()]().catch(this.logger.error);
  21. this._state = false;
  22. }
  23. }, 1000);
  24. }
  25. get data() {
  26. return this._data;
  27. }
  28. set data(value) {
  29. this._data = value;
  30. this.save();
  31. }
  32. /**
  33. * Queue Load
  34. */
  35. load() {
  36. this._queue.push('_load');
  37. }
  38. /**
  39. * Queue Save
  40. */
  41. save() {
  42. this._queue.push('_save');
  43. }
  44. _load() {
  45. try {
  46. return this._data = existsSync(this.file) ? JSON.parse(readFileSync(this.file)) : {};
  47. } catch (e) {
  48. this.logger.error(e);
  49. return this._data = {};
  50. }
  51. }
  52. async _save() {
  53. const dirname = _dirname(this.file);
  54. if (!existsSync(dirname)) await fs.mkdir(dirname, {recursive: true});
  55. await fs.writeFile(this.file, JSON.stringify(this._data, ...this._jsonargs));
  56. return this.file;
  57. }
  58. }
  59. export default Database;