forked from FGRibreau/node-redis-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis-lua.js
69 lines (54 loc) · 1.53 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
var createHash = require('crypto').createHash,
_ = require('lodash'),
sha = function(str) {return createHash('sha1').update(str).digest('hex');};
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( SCRIPTNAME , SCRIPT_PLAINTEXT, [keyed]);
* @param {String} name Script name
* @param {String} script Script string
* @param {[type]} keyed [description]
* @chainable
* @return {Redis}
*/
redis.lua = function(name, script, keyed) {
var script_sha = null;
redis.RedisClient.prototype[name] = function(){
var cb = function(){}, self = this, params;
params = [].slice.call(arguments);
if (params.length > 0 && typeof params[params.length - 1] == 'function') {
cb = params.pop();
}
if(!_.isArray(params)){
params = [params];
}
params = _.flatten(params);
params.unshift(script);
if(keyed){
cb = keyval(cb);
}
params.push(cb);
// node_redis now support eval
// https://github.com/mranney/node_redis/blob/master/index.js#L1067
this.eval.apply(this, params);
};
return this;
};
return redis;
};