eximiabots-radiox/src/client/classes/Datastore.js

104 lines
2.6 KiB
JavaScript
Raw Normal View History

2021-06-08 09:01:56 +00:00
const fs = require('fs');
const path = require('path');
module.exports = class {
constructor() {
this.map = new Map();
this.loadData();
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
loadData() {
const dir = path.join(path.dirname(__dirname), '../../datastore');
2021-08-04 07:07:11 +00:00
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
2021-06-08 09:01:56 +00:00
//console.log("");
const dataFiles = fs.readdirSync(path.join(path.dirname(__dirname), '../../datastore')).filter(f => f.endsWith('.json'));
2021-06-08 09:01:56 +00:00
for (const file of dataFiles) {
try {
const json = require(`../../../datastore/${file}`);
2021-06-08 09:01:56 +00:00
this.map.set(json.guild.id, json);
//console.log('[LOADED] ' + file + " (" + json.guild.id + ")");
//console.log(JSON.stringify(json, null, 4));
} catch (error) {
//console.log('[ERROR] Loading ' + file + ' failed');
}
}
//console.log("");
}
checkEntry(id){
2021-09-14 14:12:18 +00:00
this.loadEntry(id);
2021-06-08 09:01:56 +00:00
if(!this.map.has(id)){
this.createEntry(id);
//this.showEntry(this.getEntry(id));
} else {
//this.showEntry(this.getEntry(id));
}
}
createEntry(id){
let newData = {};
newData.guild = {};
newData.guild.id = id;
newData.statistics = {};
2021-09-02 22:21:11 +00:00
newData.state = {};
2021-06-08 09:01:56 +00:00
this.map.set(id, newData);
this.saveEntry(id, newData);
}
2021-09-09 09:44:50 +00:00
2021-09-14 14:12:18 +00:00
loadEntry(id){
const json = require(`../../../datastore/` + id + '.json');
this.map.set(id, json);
}
2021-06-08 09:01:56 +00:00
getEntry(id){
return this.map.get(id);
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
updateEntry(guild, newData) {
newData.guild.name = guild.name;
2021-09-02 22:21:11 +00:00
let date = new Date();
newData.updated = date.toISOString().substring(0, 10)
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
this.map.set(guild.id, newData);
this.saveEntry(guild.id, newData);
//this.showEntry(this.getEntry(guild.id));
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
showEntry(data){
console.log(data);
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
createTestFile () {
let newData = {
"guild": {
"id": "test",
"name": "Test"
},
"statistics": {
"test": {
"time": 0,
"used": 0
}
2021-09-02 22:21:11 +00:00
},
"state": {
2021-06-08 09:01:56 +00:00
}
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
this.updateEntry(newData.guild, newData);
}
2021-09-09 09:44:50 +00:00
2021-06-08 09:01:56 +00:00
saveEntry(file, data) {
data = JSON.stringify(data, null, 4);
2021-09-02 22:21:11 +00:00
fs.writeFile(path.join(path.dirname(__dirname), '../../datastore') + "/" + file + ".json", data, 'utf8', function(err) {
2021-06-08 09:01:56 +00:00
if (err) {
//console.log(err);
}
});
}
};