forked from djyde/StoreDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstoredb.js
100 lines (83 loc) · 3.23 KB
/
storedb.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
92
93
94
95
96
97
98
99
100
var storedb = function(collectionName){
collectionName = collectionName ? collectionName : 'default';
var err;
var cache = localStorage[collectionName] ? JSON.parse(localStorage[collectionName]) : [];
return {
insert: function(obj,callback){
obj["_id"] = new Date().valueOf();
cache.push(obj);
localStorage.setItem(collectionName,JSON.stringify(cache));
if(callback)
callback(err,obj);
},
find: function(obj, callback){
if(arguments.length == 0){
return cache;
} else {
var result = [];
for(var key in obj){
for(var i = 0; i < cache.length; i++){
if(cache[i][key] == obj[key]){
result.push(cache[i]);
}
}
}
if(callback)
callback(err,result);
else
return result;
}
},
update: function(obj,upsert,callback){
for(var key in obj){
for(var i = 0; i < cache.length; i++){
if(cache[i][key] == obj[key]){
end_loops:
for(var upsrt in upsert){
switch(upsrt){
case "$inc":
for(var newkey in upsert[upsrt]){
cache[i][newkey] = parseInt(cache[i][newkey]) + parseInt(upsert[upsrt][newkey]);
}
break;
case "$set":
for(var newkey in upsert[upsrt]){
cache[i][newkey] = upsert[upsrt][newkey];
}
break;
case "$push":
for(var newkey in upsert[upsrt]){
cache[i][newkey].push(upsert[upsrt][newkey]);
}
break;
default:
upsert['_id'] = cache[i]['_id'];
cache[i] = upsert;
break end_loops;
}
}
}
}
}
localStorage.setItem(collectionName,JSON.stringify(cache));
if(callback)
callback(err);
},
remove: function(obj,callback){
if(arguments.length == 0){
localStorage.removeItem(collectionName);
} else {
for(var key in obj){
for (var i = cache.length - 1; i >= 0; i--) {
if(cache[i][key] == obj[key]){
cache.splice(i,1);
}
}
}
localStorage.setItem(collectionName, JSON.stringify(cache));
}
if(callback)
callback(err);
}
};
};