Sélectionner une révision Git
ComplotDB.js 3,48 Kio
const fs = require('fs');
class ComplotDB{
constructor(){
this.filename = "./database/complot_db.json";
this.actors = [];
this.actions = [];
this.reasons = [];
this.sentences = [];
this.sources = [];
this.welcome = [];
this.readFile();
}
addSentence(sentence){
this.sentences.push(sentence);
this.saveFile();
}
addSource(source){
this.sources.push(source);
this.saveFile();
}
addActor(actor){
this.actors.push(actor);
this.saveFile();
}
addAction(action){
this.actions.push(action);
this.saveFile();
}
addReason(reason){
this.reasons.push(reason);
this.saveFile();
}
getAllActors(){
return this.actors;
}
getAllActions(){
return this.actions;
}
getAllReasons(){
return this.reasons;
}
getAllWelcome(){
return this.welcome;
}
#getRandomItem(liste){
return liste[Math.floor(Math.random()*liste.length)];
}
getRandomActor(){
return this.#getRandomItem(this.actors);
}
getRandomAction(){
return this.#getRandomItem(this.actions);
}
getRandomReason(){
return this.#getRandomItem(this.reasons);
}
getRandomSource(){
return this.#getRandomItem(this.sources);
}
getRandomSentence(){
return this.#getRandomItem(this.sentences);
}
getRandomWelcome(){
return this.#getRandomItem(this.welcome);
}
#enumListString(list){
let string = '';
for(let i = 0; i < list.length; i++){
string += `${i} - ${list[i]}\n`;
}
string += "\n";
return string;
}
listToString(list, title){
let content = `======== ${title} =========\n`;
content += this.#enumListString(list);
return content;
}
actorToString(){
return this.listToString(this.actors, 'Actors');
}
actionToString(){
return this.listToString(this.actions, 'Action');
}
reasonToString(){
return this.listToString(this.reasons, 'Reasons');
}
sourceToString(){
return this.listToString(this.sources, 'Sources');
}
sentenceToString(){
return this.listToString(this.sentences, 'Sentences');
}
toString(){
return 'See Base du bot...';
}
readFile(){
fs.readFile(this.filename, (err, data)=>{
if (err){
console.log("ERROR READ FILE", err);
throw err;
}
const json = JSON.parse(data);
this.actors = json.actors ? json.actors : [];
this.reasons = json.reasons ? json.reasons : [];
this.actions = json.actions ? json.actions : [];
this.sources = json.sources ? json.sources : [];
this.sentences = json.sentences ? json.sentences : [];
this.welcome = json.welcome ? json.welcome : [];
});
}
saveFile(){
let data = JSON.stringify({
actors: this.actors,
actions: this.actions,
reasons: this.reasons,
sources : this.sources,
sentences : this.sentences,
welcome: this.welcome,
});
fs.writeFile(this.filename, data, (err)=>{
if(err){
console.log("SAVE FILE ERROR", err);
}
});
}
}
const instance = new ComplotDB();
module.exports = instance;