-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdb.js
51 lines (45 loc) · 1.35 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
'use strict';
let users = {};
let tasks = {};
// we are saving everything inmemory for now
let db = {
users: proc(users),
tasks: proc(tasks)
}
function clone(obj) {
// a simple way to deep clone an object in javascript
return JSON.parse(JSON.stringify(obj));
}
// a generalised function to handles CRUD operations
function proc(container) {
return {
save(obj) {
// in JS, objects are passed by reference
// so to avoid interfering with the original data
// we deep clone the object, to get our own reference
let _obj = clone(obj);
console.log('savig', _obj);
if (!_obj.id) {
// assign a random number as ID if none exists
_obj.id = (Math.random() * 10000000) | 0;
}
container[_obj.id.toString()] = _obj;
return clone(_obj);
},
fetch(id) {
// deep clone this so that nobody modifies the db by mistake from outside
return clone(container[id.toString()]);
},
fetchAll() {
let _bunch = [];
for (let item in container) {
_bunch.push(clone(container[item]));
}
return _bunch;
},
unset(id) {
delete container[id];
}
}
}
module.exports = db;