BetterDiscordApp-v2/core/src/modules/database.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-03-07 09:12:44 +01:00
/**
* BetterDiscord Database Module
* Copyright (c) 2015-present JsSucks - https://github.com/JsSucks
* All rights reserved.
* https://github.com/JsSucks - https://betterdiscord.net
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
2018-05-28 02:52:12 +02:00
import Datastore from 'nedb';
2018-03-07 09:12:44 +01:00
2018-05-28 02:52:12 +02:00
export default class Database {
2018-03-07 09:12:44 +01:00
constructor(dbPath) {
this.exec = this.exec.bind(this);
this.update = this.update.bind(this);
2018-03-10 04:05:12 +01:00
this.init(dbPath);
//this.db.emotes.loadDatabase();
//this.db = new Datastore({ filename: dbPath, autoload: true });
}
async init(dbPath) {
this.db = {
storage: new Datastore({ filename: `${dbPath}/storage`, autoload: true })
};
2018-03-07 09:12:44 +01:00
}
async update(cmd) {
2018-03-10 04:05:12 +01:00
const db = cmd.db ? this.db[cmd.db] : this.db.storage;
2018-03-07 09:12:44 +01:00
return new Promise((resolve, reject) => {
2018-03-10 04:05:12 +01:00
db.update(cmd.args, cmd.data, { upsert: true }, (err, docs) => {
2018-03-07 09:12:44 +01:00
if (err) return reject(err);
2018-03-10 04:05:12 +01:00
db.persistence.compactDatafile();
2018-03-07 09:12:44 +01:00
resolve(docs);
});
});
}
2018-03-10 04:05:12 +01:00
async loadDatabase(db) {
return new Promise((resolve, reject) => {
db.loadDatabase();
resolve();
});
}
2018-03-07 09:12:44 +01:00
async find(cmd) {
2018-03-10 04:05:12 +01:00
const db = cmd.db ? this.db[cmd.db] : this.db.storage;
let args = cmd.args;
if (cmd.regex) args = { [cmd.regex.param]: new RegExp(cmd.regex.source, cmd.regex.flags) };
2018-03-07 09:12:44 +01:00
return new Promise((resolve, reject) => {
2018-03-10 04:05:12 +01:00
db.find(args, (err, docs) => {
2018-03-07 09:12:44 +01:00
if (err) return reject(err);
resolve(docs);
});
});
}
async exec(cmd) {
switch (cmd.action) {
2018-08-15 08:01:47 +02:00
case 'update':
return this.update(cmd);
case 'find':
return this.find(cmd);
2018-03-07 09:12:44 +01:00
}
throw 'Invalid Command';
}
}