-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfake_db.js
71 lines (59 loc) · 1.26 KB
/
fake_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
var objects = {};
var foreignKey = 1;
var fakeDb = {
destroy: async(immutabled(destroy)),
upsert: async(immutabled(upsert)),
list: async(immutabled(list)),
get: async(immutabled(get))
};
function immutabled(func) {
return function(obj) {
return clone(func(clone(obj)));
};
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function async(func) {
return function(arg, callback) {
var latency = Math.random() * 100;
var result;
try {
result = func(arg);
setTimeout(function() {
callback(null, result);
}, latency);
return;
} catch (err) {
setTimeout(function() {
callback(err.toString(), null);
}, latency);
return;
}
};
}
function list(length) {
return Object.keys(objects).slice(0, length).map(get);
}
function get(id) {
if (!objects[id]) {
throw 'Object does not exist.';
} else {
return objects[id];
}
}
function upsert(obj) {
if (Object.prototype.toString.call(obj) !== '[object Object]') {
throw 'You can only create plain objects.'
} else {
obj.id = obj.id || foreignKey++;
objects[obj.id] = obj;
return obj;
}
}
function destroy(id) {
var obj = get(id);
delete objects[id];
return obj;
}
module.exports = fakeDb;