-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (104 loc) · 1.98 KB
/
index.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/**
* get `ejdb` adapter with `EJDB` instance.
*
* @param {EJDB} ej
* @return {Function}
*/
module.exports = function(ej){
if (!ej) throw new TypeError('expected: EJDB instance');
return function(model){
model._sync = exports;
model.ej = ej;
}
};
/**
* ejdb
*/
exports.name = 'ejdb';
/**
* Save.
*
* @param {Function} fn
*/
exports.save = function(fn){
var name = this.model.modelName
, ej = this.model.ej
, obj = this.toJSON()
, self = this;
ej.save(name, [obj], function(err, oids){
if (err) return fn(err);
obj.id = oids[0];
fn(null, obj);
});
};
/**
* Update.
*
* @param {Function} fn
*/
exports.update = function(fn){
var name = this.model.modelName
, ej = this.model.ej
, obj = this.toJSON()
, self = this;
ej.update(name, [obj], function(err){
if (err) return fn(err);
fn(null, obj);
});
};
/**
* Get all with the given `query`, `[or]`, `[hints]` and `fn`.
*
* @param {Object} query
* @param {Array} or
* @param {Object} hints
* @param {Function} fn
*/
exports.all = function(){
var args = [].slice.call(arguments)
, name = this.modelName
, ej = this.ej;
var fn = args.pop();
args.unshift(name);
args.push(done);
ej.find.apply(ej, args);
function done(err, c){
if (err) return fn(err);
expand(c, fn);
}
};
/**
* Get a user with `query`, `[or]`, `[hints]` and `fn`.
*
* @param {Object} query
* @param {Array} or
* @param {Object} hints
* @param {Function} fn
*/
exports.get = function(){
var args = [].slice.call(arguments)
, name = this.modelName
, ej = this.ej;
// col
args.unshift(name);
// id
args[1] = 'object' != typeof args[1]
? { _id: args[1] }
: args[1];
// one
ej.findOne.apply(ej, args);
};
/**
* Expand the given cursor.
*
* @param {Cursor} c
* @param {Function} fn
* @return {Array}
*/
function expand(c, fn){
setImmediate(function(){
var all = [];
while (c.next()) all.push(c.object());
fn(null, all);
});
}