-
Notifications
You must be signed in to change notification settings - Fork 20
/
persist.js
75 lines (64 loc) · 2 KB
/
persist.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
var data = {}
, dbc = require('dbc')
, _ = require('underscore')
, q = require('q')
function wrap(v) {
return q.fcall(function () {return v;});
}
module.exports = {
insert: function (collectionName, resource) {
dbc.isObject(resource, "resource is not an object");
validateCollectionName(collectionName);
var c = getCollection(collectionName);
var withId = _.extend(resource, {id: nextId(c)});
c.push(withId);
return wrap(withId);
},
all: function (collectionName) {
validateCollectionName(collectionName);
var c = getCollection(collectionName);
return wrap(c);
},
get: function (collectionName, id) {
validateCollectionName(collectionName);
var c = getCollection(collectionName);
console.log('stringified collection:' + JSON.stringify(c));
var resource = _.find(c, function (r) {
return r.id == id;
});
console.log(typeof resource);
dbc.assert(resource && (typeof resource) === 'object');
return wrap(resource);
},
update: function (collectionName, id, resource) {
validateCollectionName(collectionName);
var c = getCollection(collectionName);
data[collectionName] = _.reject(c, function (x) {
return x.id == id;
});
var updated = _.extend(resource, {id: id});
data[collectionName].push(updated);
return wrap(updated);
},
delete: function (collectionName, id) {
validateCollectionName(collectionName);
var c = getCollection(collectionName);
data[collectionName] = _.reject(c, function (x) {
return x.id == id;
});
}
};
function validateCollectionName(collectionName) {
dbc.assert(collectionName && (typeof collectionName) === 'string' && collectionName.length > 0,
'collectionName is invalid');
}
function nextId(collection) {
if (collection.length === 0) return 1;
return _.max(collection, function(resource) {
return resource.id;
}).id + 1;
}
function getCollection(name) {
data[name] = data[name] || [];
return data[name];
}