-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
executable file
·91 lines (71 loc) · 1.74 KB
/
db.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
function later(fn){
setTimeout(fn, 0);
}
function findAll(query, callback){
var model = this;
later(function(){
callback(null, model._items.filter(function(item){
return !Object.keys(query).some(function(key){
return item[key] !== query[key];
});
}));
});
}
function find(query, callback){
this.findAll(query, function(error, results){
if(error){
return callback(error);
}
callback(null, results[0]);
});
}
function update(query, newData, callback){
this.find(query, function(error, item){
if(error){
return callback(error);
}
for(var key in newData){
item[key] = newData[key];
}
callback(null, item);
});
}
function remove(query, callback){
var model = this;
this.find(query, function(error, item){
if(error){
return callback(error);
}
if(item){
model._items.splice(model._items.indexOf(item), 1);
return callback();
}
callback();
});
}
function create(item, callback){
var model = this;
later(function(){
item.id = model._id++;
model._items.push(item);
callback(null, item);
});
}
var models = {};
function makeFakeModel(name){
var model = {
_id: 0,
_items: []
};
model.create = create.bind(model);
model.find = find.bind(model);
model.update = update.bind(model);
model.remove = remove.bind(model);
model.findAll = findAll.bind(model);
models[name] = model;
}
var righto = require('righto');
makeFakeModel('Users');
makeFakeModel('Addresses');
makeFakeModel('Profiles');
module.exports = models;