blob: 6c01df0ad5d60414cd88992f6c420ba66443a0bc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
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;
|