forked from jazzpool/redis-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (98 loc) · 2.98 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const redis = require('redis');
const {EventEmitter} = require('events');
const Response = require('./response');
module.exports = class Redis extends EventEmitter {
constructor(config) {
super();
this.config = config;
}
/**
* @public
* @return {Promise<*>}
*/
connect() {
return new Promise((resolve, reject) => {
this.connection = redis.createClient(this.config.port, this.config.host, {
prefix: this.config.prefix || null
});
if (this.config.password) {
this.connection.auth(this.config.password, err => {
if (err) {
this.emit('error', err);
reject(err);
}
});
}
this.connection.on('ready', data => {
this.emit('ready');
resolve(data);
});
this.connection.on('error', err => {
this.emit('error', err);
reject(err);
});
this.connection.on('end', data => this.emit('end', data));
});
}
/**
* @public
* @param {string} command
* @param rest
* @return {Promise<*>}
*/
call(command, ...rest) {
return new Response(new Promise((resolve, reject) => {
if (this.connection[command]) {
this.connection[command].apply(this.connection, rest.concat((err, data) => {
if (err) {
this.emit('error', err);
reject(err);
}
resolve(data);
}));
} else {
reject(new Error(`No such command: ${command}`));
}
}));
}
/**
* @public
* @param {array} cmds
* @return {Promise<array>}
*/
multi(cmds) {
return new Response(new Promise((resolve, reject) => {
this.connection.multi(cmds).exec((err, data) => {
if (err) {
this.emit('error', err);
reject(err);
}
resolve(data);
});
}));
}
/**
* @public
* @param {object} shapes
* @return {Promise<object>}
*/
shape(shapes) {
const [commands, keys] = Object.keys(shapes).reduce(([commands, entries], entry) => ([
commands.concat([shapes[entry]]),
entries.concat(entry),
]), [[], []]);
return new Promise((resolve, reject) => {
this.connection.multi(commands).exec((err, replies) => {
if (err) {
this.emit('error', err);
reject(err);
}
resolve(replies.reduce((acc, reply, replyIndex) => {
const key = keys[replyIndex];
acc[key] = reply
return acc
}, {}));
})
})
}
}