var Q = require('q'); var format = require('util').format; var low = require('lowdb'); low.mixin(low.mixin(require('underscore-db'))); /** * OKDB! * Minimal interface over a database of named collections of documents. */ function OKDB(options) { if (!(this instanceof OKDB)) return new OKDB(options); options = options || {}; var type; if (typeof options === 'string') type = options; else type = options.type; if (!type) throw new Error('No DB type provided'); switch (type) { case 'fs': return FSDB(options); default: throw new Error('Invalid DB type'); } } /** * DB implementation backed by a JSON file. * TODO Incomplete */ function FSDB(options) { if (!(this instanceof FSDB)) return new FSDB(options); options = options || {}; var name = options.name || 'db'; var filename = name + '.json'; this._db = low(filename); } FSDB.prototype._resolve = function(data, success) { success = typeof success === 'undefined' ? true : success; return Q.Promise(function resolvePromise(resolve, reject) { if (success) resolve(data); else reject(data); }); }; FSDB.prototype.get = function(collection, id) { var data = this._db(collection).get(id); return this._resolve(data); }; FSDB.prototype.getMeta = function() { var data = this._db('meta').first(); return this._resolve(data || {}); }; FSDB.prototype.getAll = function(collection) { var data = this._db(collection).toArray(); return this._resolve(data || []); }; module.exports = OKDB;