Skip to content

Commit

Permalink
fix DB
Browse files Browse the repository at this point in the history
  • Loading branch information
oonqt committed May 27, 2021
1 parent 429991d commit 97d3c3e
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions utils/JsonDB.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ class JsonDB {
*/
data() {
if (!fs.existsSync(this.dbfile)) {
return this.model();
const data = this.model();
this.rawWrite(data);
return data;
} else if (this.cache) {
return this.cache;
} else {
const data = this.model(JSON.parse(fs.readFileSync(this.dbfile, 'utf8')));
this.cache = data;
this.rawWrite(data); // we are writing in case the model was updated, that way changes are reflected. this also auto-caches
return data;
}
}
Expand All @@ -37,20 +39,27 @@ class JsonDB {
}

/**
*
* @param {object} data Data to write to DB
* @returns {void}
* @private
*/
write(_data) {
const data = this.model({ ...this.data(), ..._data });

rawWrite(data) {
this.cache = data;

fs.writeFileSync(
this.dbfile,
JSON.stringify(data)
);
}

/**
*
* @param {object} data Data to write to DB
* @returns {void}
*/
write(_data) {
const data = this.model({ ...this.data(), ..._data });

this.rawWrite(data);
}
}

module.exports = JsonDB;

0 comments on commit 97d3c3e

Please sign in to comment.