Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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
- *
- */
- class BasicDB {
- /**
- * Very simple function, simply save a JSON to the given filepath
- *
- */
- saveJSONToFile(file, json) {
- if(!fs.existsSync(path.dirname(file))){
- fs.mkdirSync(path.dirname(file));
- } else {
- const out = JSON.stringify(json);
- fs.writeFileSync(file, out);
- }
- }
- /**
- * Very simple function; simply load a JSON from the passed file.
- *
- */
- loadJSONFromFile(file) {
- if(!fs.existsSync(path.dirname(file))) {
- throw 'No existing data! Searched in the following directory: ' + path.dirname(file);
- } else {
- const contents = fs.readFileSync(file);
- return JSON.parse(contents);
- }
- }
- }
- module.exports = BasicDB;
- ///////////////////////////////////////////////////
- /**
- * ObjectDB is an extensible class meant to build upon BasicDB.
- *
- * The idea is, allow for saving objects that extend the Data class
- *
- */
- const BasicDB = require('./basic-db');
- class ObjectDB extends BasicDB {
- /**
- *
- */
- saveData(data, filepath, name){
- let json = [];
- for(d in data){
- json.push(d.toJSON());
- }
- this.saveJSONToFile(path.resolve(filepath, name), json);
- }
- /**
- * THIS IS TERRIBLE DESIGN BELOW; NEEDS CORRECTION VIA SOME FLAVOR OF POLYMORPHISM
- *
- */
- //Return JSON trades from filepath, one set in class as default
- loadData(DataClass, filepath, name) {
- const json = this.loadJSONFromFile(path.resolve(filepath, name));
- let data = [];
- for(j in json){
- data.push(new DataClass(j));
- }
- return data;
- }
- }
- module.exports = ObjectDB;
- //////////////////////////////////////////
- const Util = require('../util/util')
- //Extend this, for the use of the ObjectDB
- class JSONData {
- toJSON(){ return Util.instanceToObj(this); }
- }
- module.exports = JSONData;
Advertisement
Add Comment
Please, Sign In to add comment