-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.js
51 lines (43 loc) · 1.32 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const fs = require('fs');
function _getSavePath(mdl) {
return "./saves/" + mdl.toLowerCase() + "\\";
}
class DB {
constructor(client) {
this.client = client;
}
async save(mdl, name, data) {
if (process.env.MONGO_DB_URL) {
const collection = this.client.mongo.db(mdl).collection(name);
await collection.replaceOne({}, data, { upsert: true });
console.log(mdl + " Database Saved");
} else {
var string = JSON.stringify(data);
if (!fs.existsSync(_getSavePath(mdl))) fs.mkdirSync(_getSavePath(mdl));
fs.writeFile(_getSavePath(mdl) + name + ".json", string, err => {if (err != null) console.log(err)});
console.log(mdl + " JSON Data Saved");
}
}
async load(mdl, name, fallback) {
if (!await this.saveExists(mdl, name)) {
this.save(mdl, name, fallback);
return fallback;
}
if (process.env.MONGO_DB_URL) {
var res = await this.client.mongo.db(mdl).collection(name).findOne();
if (res._id) delete res._id;
return res;
} else {
var string = fs.readFileSync(_getSavePath(mdl) + name + ".json");
return JSON.parse(string);
}
}
async saveExists(mdl, name) {
if (process.env.MONGO_DB_URL) {
return await this.client.mongo.db(mdl).listCollections({name: name}).hasNext();
} else {
return fs.existsSync(_getSavePath(mdl) + name + ".json");
}
}
};
module.exports = exports = DB;