const level = require('level'); const sub = require('level-sublevel'); const search = require('level-search'); var path = require('path'); var DIR = path.dirname(__filename); class Database { constructor(){ console.log("Constructing database!") this.db = sub(level(DIR + "/mafaldadb", {valueEncoding: 'json'})); this.index = search(this.db, 'search'); // this.createSearchStream = this.createSearchStream.bind(this); } open(callback){ return this.db.open(callback); } close(callback){ return this.db.close(callback); } put(key, value){ return new Promise( (res,rej) => { this.db.put(key, value, (err,values) => { if(err) return rej(err); return res(values); }); }); } get(key){ return new Promise( (res,rej) => { this.db.get(key, (err,values) => { if(err) return rej(err); return res(values); }); }); } del(key, options, callback){ return this.db.del(key, options, callback); } batch(array, options, callback){ return this.db.batch(array, options, callback); } isOpen(){ return this.db.isOpen(); } isClosed(){ return this.db.isClosed(); } createReadStream(options) { const results = []; return new Promise((res,rej) => { this.db.createReadStream(options) .on('data', function (data) { results.push(data.value); }) .on('error', function (err) { rej(err); }) .on('close', function () { }) .on('end', function () { res(results); }); }); } createKeyStream(options){ return this.db.createKeyStream(options); } createValueStream(options){ return this.db.createValueStream(options); } createSearchStream(keys, options) { const results = []; return new Promise((res,rej) => { this.index.createSearchStream(keys,options) .on('data', function (data) { results.push(data.value); }) .on('error', function (err) { rej(err); }) .on('close', function () { }) .on('end', function () { res(results); }); }); } read(options) { return this.createReadStream(options); } search(keys, options) { return this.createSearchStream(keys, options); } }; let database = null; function getSingleton() { return database = (database === null ? new Database() : database); } module.exports = getSingleton();