-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.js
106 lines (74 loc) · 2.04 KB
/
data.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
101
102
103
104
105
106
if (process.env.REDISTOGO_URL) {
console.log('Found redis!')
var rtg = require("url").parse(process.env.REDISTOGO_URL);
var redis = require("redis").createClient(rtg.port, rtg.hostname);
redis.auth(rtg.auth.split(":")[1]);
} else {
var redis = require("redis").createClient();
}
redis.on("error", function (err) {
console.log("Error " + err);
});
function ObjSet(singular, groupName) {
if (!groupName) { groupName = singular + 's'; }
function objKey(key) {
return singular + ':' + key;
}
this.makeUpdateProp = function(obj, key) {
return function(propKey, value, cb) {
obj[propKey] = value;
redis.hset(objKey(key), propKey, value, cb);
}
};
this.add = function(key, obj, cb) {
var counter = 2;
function maybeCallback(err, result) {
counter--;
if (err) {
console.log('Error: ' + err);
}
if (counter === 0 && cb) {
cb(err, result);
}
}
redis.sadd(groupName, key, maybeCallback);
redis.hmset(objKey(key), obj, maybeCallback);
};
this.get = function (key, cb) {
redis.hgetall(objKey(key), cb);
};
this.delete = function(key, cb) {
console.log('Deleting key ' + key + ' from ' + groupName);
var counter = 2;
function maybeCallback() {
counter--;
if (counter === 0 && cb) {
cb();
}
}
redis.del(objKey(key), maybeCallback);
redis.srem(groupName, key, maybeCallback);
}
this.getAll = function(cb) {
console.log('Looking up ' + groupName);
redis.smembers(groupName, function(err, keys) {
var keysLeft = keys.length;
var reply = {}
keys.forEach(function(key) {
this.get( key, function(err, obj) {
if (err) {
console.log(err);
} else {
console.log('Found ' + obj + ' at key ' + key);
}
reply[key] = obj;
keysLeft--;
if (cb && keysLeft === 0) {
cb(reply);
}
} );
}.bind(this));
}.bind(this));
}
}
module.exports = ObjSet;