-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
84 lines (70 loc) · 2.69 KB
/
index.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
module.exports = RedisJSONify;
RedisJSONify.blacklist = ["info"];
function RedisJSONify (redis, opts) {
var lastArgType;
opts = opts || {};
//save a reference to the real send_command method
var send_command = redis.internal_send_command || redis.send_command;
//define the send_command proxy method
redis.internal_send_command = redis.send_command = function (command, args, callback) {
var objectMode = false;
var applyArgs;
//don't do json stuff on blacklisted commands or if we are not ready yet
if (!this.ready || ~RedisJSONify.blacklist.indexOf(command) || (command && command.command && ~RedisJSONify.blacklist.indexOf(command.command))) {
return send_command.apply(redis, arguments);
}
if (typeof command === 'object') {
objectMode = true;
callback = command.callback;
args = command.args;
command.callback = finish;
}
else if (!callback) {
lastArgType = typeof args[args.length - 1];
if (lastArgType === "function" || lastArgType === "undefined") {
callback = args.pop();
}
}
//loop through each arg converting to JSON if possible
args.forEach(function (arg, ix) {
//only stringify the key if that has been requested
if (ix === 0 && !opts.jsonKey) {
//don't do anything: args[ix] = arg;
}
//make sure the arg is not a buffer
else if (!(arg instanceof Buffer)) {
args[ix] = JSON.stringify(arg);
}
});
if (objectMode) {
applyArgs = [command];
}
else {
applyArgs = [command, args, finish];
}
//call the real send_command method
send_command.apply(redis, applyArgs);
function finish (err, result) {
if (Array.isArray(result)) {
//loop through each array element
result.forEach(function (value, ix) {
if (!value instanceof Buffer) {
result[ix] = JSON.parse(value);
}
});
}
else if (!(result instanceof Buffer) && result !== "OK") {
try {
result = JSON.parse(result);
}
catch (e) {
console.error("JSON.parse failed on command '%s' with value"
+ " '%s'. This command may need to be black listed"
, command, result);
}
}
return callback && callback(err, result);
}
};
return redis;
}