-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathredis-lua.js
84 lines (72 loc) · 1.79 KB
/
redis-lua.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
var
createHash = require('crypto').createHash,
sha = function(str) {return createHash('sha1').update(str).digest('hex');};
function eval_cmd(db, script, params, cb) {
params.unshift(script);
params.unshift('eval');
params.push(cb);
db.send_command.apply(db, params);
}
function evalsha_cmd(db, script_sha, params, cb) {
params.unshift(script_sha);
params.unshift('evalsha');
params.push(cb);
db.send_command.apply(db, params);
}
function keyval(cb) {
return function(err, res) {
var
hash = {},
i,
key,
val;
if (err) {
cb(err);
} else if (res.length % 2 !== 0 ) {
cb('result length not even');
} else {
for(i=0; i<res.length; i +=2) {
key = res[i].toString();
val = res[i+1];
hash[key] = val;
}
cb(null, hash);
}
};
}
exports.attachLua = function(redis) {
redis.lua = function(name, num_keys, script, keyed) {
var
script_sha;
redis.RedisClient.prototype[name] = function() {
var
cb,
db,
that = this,
params;
params = [].slice.call(arguments, 0, arguments.length);
if (params.length > 0 && typeof params[params.length-1] == 'function') {
cb = params.pop();
} else {
cb = function(){};
}
if (keyed) {
cb = keyval(cb);
}
params.unshift(num_keys);
if (script_sha) {
evalsha_cmd(that, script_sha, params, function(err, res) {
if (err && err.message.indexOf('NOSCRIPT') > 0) {
eval_cmd(that, script, params.slice(2, -1), cb);
} else {
cb(err, res);
}
});
} else {
script_sha = script_sha || sha(script);
eval_cmd(that, script, params, cb);
}
};
};
return redis;
};