UNPKG

dbjsond

Version:

Quick and easy database for Node.js.

119 lines (91 loc) 2.64 kB
const fs = require('fs'); class Database { constructor(type = ':memory') { this._tempMemory = new Object(); this._collection = false; if(type != ':memory') { this.openDatabaseFile(type); this._url = type; } } add(name, value, collection = this._collection) { if(!name || !value) throw new Error('[Database] name or value not set (add)'); if(!collection) { this._tempMemory[name] = value; } else { if(!this._tempMemory[collection]) this._tempMemory[collection] = new Object(); this._tempMemory[collection][name] = value; } return this; } remove(name, collection = this._collection) { if(!name) throw new Error('[Database] name not set (remove)'); if(!collection) { delete this._tempMemory[name]; } else { delete this._tempMemory[collection][name]; } return this; } get(name, collection = this._collection) { if(!name) throw new Error('[Database] name not set (get)'); if(!collection) { return this._tempMemory[name]; } else { if(!this._tempMemory[collection]) return undefined; return this._tempMemory[collection][name]; } } getAll(collection) { if(collection) { if(!this._tempMemory[collection]) return undefined; return this._tempMemory[collection]; } else { return this._tempMemory; } } setCollection(collection) { if(!this._tempMemory[collection]) this._tempMemory[collection] = new Object(); this._collection = collection; return this; } unsetCollection() { this._collection = false; return this; } removeCollection(collection) { delete this._tempMemory[collection]; return this; } save() { fs.writeFile(this._url, JSON.stringify(this._tempMemory), (error) => { if(!error) { console.log('[Database] Save'); } else { console.log('[Database] ', error); } }); } autosave(data, timer = 10) { setInterval(() => { fs.writeFile(this._url, JSON.stringify(data), (error) => { if(!error) { console.log('[Database] Autosave'); } else { console.log('[Database] ', error); } }); }, timer * 1000); } openDatabaseFile(url) { const data = fs.readFileSync(url, 'utf-8'); if(data !== null) { try { this._tempMemory = JSON.parse(data); } catch(e) { this._tempMemory = new Object(); } } } } module.exports = Database;