aboutsummaryrefslogtreecommitdiff
path: root/src/legacy/jsonDb.js
diff options
context:
space:
mode:
authorSin-MacBook <[email protected]>2020-08-10 23:44:20 +0200
committerSin-MacBook <[email protected]>2020-08-10 23:44:20 +0200
commit2a53887abba882bf7b63aeda8dfa55fdb3ab8792 (patch)
treead7a95eb41faa6ff13c3142285cdc0eb3ca92183 /src/legacy/jsonDb.js
downloadmodmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.tar.xz
modmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.zip
clean this up when home
Diffstat (limited to 'src/legacy/jsonDb.js')
-rw-r--r--src/legacy/jsonDb.js71
1 files changed, 71 insertions, 0 deletions
diff --git a/src/legacy/jsonDb.js b/src/legacy/jsonDb.js
new file mode 100644
index 0000000..d2e8ca1
--- /dev/null
+++ b/src/legacy/jsonDb.js
@@ -0,0 +1,71 @@
+const fs = require('fs');
+const path = require('path');
+const config = require('../config');
+
+const dbDir = config.dbDir;
+
+const databases = {};
+
+/**
+ * @deprecated Only used for migrating legacy data
+ */
+class JSONDB {
+ constructor(path, def = {}, useCloneByDefault = false) {
+ this.path = path;
+ this.useCloneByDefault = useCloneByDefault;
+
+ this.load = new Promise(resolve => {
+ fs.readFile(path, {encoding: 'utf8'}, (err, data) => {
+ if (err) return resolve(def);
+
+ let unserialized;
+ try { unserialized = JSON.parse(data); }
+ catch (e) { unserialized = def; }
+
+ resolve(unserialized);
+ });
+ });
+ }
+
+ get(clone) {
+ if (clone == null) clone = this.useCloneByDefault;
+
+ return this.load.then(data => {
+ if (clone) return JSON.parse(JSON.stringify(data));
+ else return data;
+ });
+ }
+
+ save(newData) {
+ const serialized = JSON.stringify(newData);
+ this.load = new Promise((resolve, reject) => {
+ fs.writeFile(this.path, serialized, {encoding: 'utf8'}, () => {
+ resolve(newData);
+ });
+ });
+
+ return this.get();
+ }
+}
+
+function getDb(dbName, def) {
+ if (! databases[dbName]) {
+ const dbPath = path.resolve(dbDir, `${dbName}.json`);
+ databases[dbName] = new JSONDB(dbPath, def);
+ }
+
+ return databases[dbName];
+}
+
+function get(dbName, def) {
+ return getDb(dbName, def).get();
+}
+
+function save(dbName, data) {
+ return getDb(dbName, data).save(data);
+}
+
+module.exports = {
+ get,
+ save,
+};