-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.js
49 lines (43 loc) · 1.48 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
const redis = require('redis');
const objectDecorator = require('./object-decorator');
const objectPromisify = require('./object-promisify');
const redisCommands = require('./redis-commands');
const redisClients = new Map();
/**
* @return RedisClient
*/
const AsyncRedis = function (args=null) {
if (args) {
const serializedArgs = JSON.stringify(args);
if (!redisClients.has(serializedArgs)) {
redisClients.set(serializedArgs, Array.isArray(args) ? redis.createClient(...args) : redis.createClient(args));
}
this.setup(redisClients.get(serializedArgs));
}
};
AsyncRedis.prototype.setup = function(redisClient) {
this.__redisClient = redisClient;
const commandConfigs = redisCommands(redisClient);
objectDecorator(redisClient, (name, method) => {
if (commandConfigs.commands.has(name)) {
objectPromisify(this, redisClient, name);
} else if (commandConfigs.queueCommands.has(name)) {
return (...args) => {
const multi = method.apply(redisClient, args);
return objectDecorator(multi, (multiName, multiMethod) => {
if (commandConfigs.multiCommands.has(multiName)) {
return objectPromisify(multi, multiMethod);
}
return multiMethod;
});
}
}
});
};
AsyncRedis.createClient = (...args) => new AsyncRedis(args);
AsyncRedis.decorate = (redisClient) => {
const asyncClient = new AsyncRedis();
asyncClient.setup(redisClient);
return asyncClient;
};
module.exports = AsyncRedis;