Luiserebii

behold the terror

Jun 27th, 2019
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * BasicDB is an extensible class meant to provide basic loading, saving, and backing up of JSON files. Has no state, makes minimal assumptions, and provides low-level functions
  3.  *
  4.  */
  5.  
  6. class BasicDB {
  7.  
  8.   /**
  9.    * Very simple function, simply save a JSON to the given filepath
  10.    *
  11.    */
  12.  
  13.   saveJSONToFile(file, json) {
  14.     if(!fs.existsSync(path.dirname(file))){
  15.       fs.mkdirSync(path.dirname(file));
  16.     } else {
  17.       const out = JSON.stringify(json);
  18.       fs.writeFileSync(file, out);
  19.     }
  20.   }
  21.  
  22.   /**
  23.    * Very simple function; simply load a JSON from the passed file.
  24.    *
  25.    */
  26.   loadJSONFromFile(file) {
  27.     if(!fs.existsSync(path.dirname(file))) {
  28.       throw 'No existing data! Searched in the following directory: ' + path.dirname(file);
  29.     } else {
  30.       const contents = fs.readFileSync(file);
  31.       return JSON.parse(contents);
  32.     }
  33.   }
  34.  
  35. }
  36.  
  37. module.exports = BasicDB;
  38.  
  39.  
  40. ///////////////////////////////////////////////////
  41.  
  42. /**
  43.  * ObjectDB is an extensible class meant to build upon BasicDB.
  44.  *
  45.  * The idea is, allow for saving objects that extend the Data class
  46.  *
  47.  */
  48.  
  49. const BasicDB = require('./basic-db');
  50.  
  51. class ObjectDB extends BasicDB {
  52.  
  53.   /**
  54.    *
  55.    */
  56.   saveData(data, filepath, name){
  57.  
  58.     let json = [];
  59.     for(d in data){
  60.       json.push(d.toJSON());
  61.     }
  62.     this.saveJSONToFile(path.resolve(filepath, name), json);
  63.  
  64.   }
  65.  
  66.   /**
  67.    * THIS IS TERRIBLE DESIGN BELOW; NEEDS CORRECTION VIA SOME FLAVOR OF POLYMORPHISM
  68.    *
  69.    */
  70.   //Return JSON trades from filepath, one set in class as default
  71.   loadData(DataClass, filepath, name) {
  72.  
  73.     const json = this.loadJSONFromFile(path.resolve(filepath, name));
  74.     let data = [];
  75.     for(j in json){
  76.       data.push(new DataClass(j));
  77.     }
  78.     return data;
  79.  
  80.   }
  81.  
  82. }
  83.  
  84. module.exports = ObjectDB;
  85.  
  86. //////////////////////////////////////////
  87.  
  88. const Util = require('../util/util')
  89.  
  90. //Extend this, for the use of the ObjectDB
  91. class JSONData {
  92.  
  93.   toJSON(){ return Util.instanceToObj(this); }
  94.  
  95. }
  96.  
  97. module.exports = JSONData;
Advertisement
Add Comment
Please, Sign In to add comment