-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (71 loc) · 1.65 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
/**
* Module dependencies
*/
var uuid = require('uuid').v4;
var debug = require('debug')('simple-db-memory');
/**
* Keep an in memory list of buckets
*/
var buckets = {};
/**
* Implement the database in memory
*/
var db = exports;
db.buckets = function(cb) {
debug('buckets');
cb(null, {data: Object.keys(buckets)});
};
db.count = function(id, cb) {
debug('count', id);
getBucket(id, function(bucket) {
cb(null, {data: Object.keys(bucket).length});
});
};
db.keys = function(id, cb) {
debug('keys', id);
getBucket(id, function(bucket) {
cb(null, {data: Object.keys(bucket)});
});
};
db.get = function(id, key, cb) {
debug('get', id, key);
getBucket(id, function(bucket) {
cb(null, {data: clone(bucket[key])});
});
};
db.post = function(id, body, cb) {
debug('post', id, body);
getBucket(id, function(bucket) {
var key = uuid();
bucket[key] = clone(body);
cb(null, {key: key});
}, true);
};
db.put = function(id, key, body, cb) {
debug('put', id, key, body);
getBucket(id, function(bucket) {
bucket[key] = clone(body);
cb(null, {});
}, true);
};
db.remove = function(id, key, cb) {
debug('remove', id, key);
getBucket(id, function(bucket) {
delete bucket[key];
cb(null, {});
});
};
db.exists = function(id, key, cb) {
debug('exists', id, key);
getBucket(id, function(bucket) {
cb(null, {data: typeof bucket[key] !== 'undefined'});
});
};
function getBucket(id, cb, create) {
var bucket = buckets[id];
if (create && !bucket) bucket = buckets[id] = {};
cb(bucket || {});
}
function clone(data) {
return typeof data !== 'undefined' ? JSON.parse(JSON.stringify(data)) : null;
}