-
Notifications
You must be signed in to change notification settings - Fork 3
/
Client.ts
226 lines (189 loc) · 5.74 KB
/
Client.ts
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import EventEmitter from 'events';
import { RedisClientOptions, createClient } from 'redis';
import { parseResponse } from './parseResponse';
import { JSONResponse } from './responses';
export enum Command {
AUTH = 'AUTH',
AOFSHRINK = 'AOFSHRINK',
BOUNDS = 'BOUNDS',
CHANS = 'CHANS',
DEL = 'DEL',
DELCHAN = 'DELCHAN',
GC = 'GC',
HOOKS = 'HOOKS',
HEALTHZ = 'HEALTHZ',
PDEL = 'PDEL',
PERSIST = 'PERSIST',
TTL = 'TTL',
DELHOOK = 'DELHOOK',
DROP = 'DROP',
EXPIRE = 'EXPIRE',
INFO = 'INFO',
SET = 'SET',
FSET = 'FSET',
GET = 'GET',
OUTPUT = 'OUTPUT',
PING = 'PING',
FLUSHDB = 'FLUSHDB',
KEYS = 'KEYS',
WITHIN = 'WITHIN',
READONLY = 'READONLY',
SERVER = 'SERVER',
SETCHAN = 'SETCHAN',
SETHOOK = 'SETHOOK',
STATS = 'STATS',
RENAME = 'RENAME',
RENAMENX = 'RENAMENX',
INTERSECTS = 'INTERSECTS',
CONFIG = 'CONFIG',
JGET = 'JGET',
JSET = 'JSET',
JDEL = 'JDEL',
NEARBY = 'NEARBY',
PDELCHAN = 'PDELCHAN',
PDELHOOK = 'PDELHOOK',
SCAN = 'SCAN',
SEARCH = 'SEARCH',
}
export enum SubCommand {
FIELD = 'FIELD',
EX = 'EX',
NX = 'NX',
XX = 'XX',
WITHFIELDS = 'WITHFIELDS',
CURSOR = 'CURSOR',
LIMIT = 'LIMIT',
BUFFER = 'BUFFER',
NOFIELDS = 'NOFIELDS',
MATCH = 'MATCH',
OBJECT = 'OBJECT',
TILE = 'TILE',
QUADKEY = 'QUADKEY',
HASH = 'HASH',
BOUNDS = 'BOUNDS',
GET = 'GET',
CIRCLE = 'CIRCLE',
POINT = 'POINT',
OBJECTS = 'OBJECTS',
HASHES = 'HASHES',
IDS = 'IDS',
COUNT = 'COUNT',
POINTS = 'POINTS',
STRING = 'STRING',
META = 'META',
FENCE = 'FENCE',
DETECT = 'DETECT',
COMMANDS = 'COMMANDS',
REWRITE = 'REWRITE',
ASC = 'ASC',
DESC = 'DESC',
WHERE = 'WHERE',
SECTOR = 'SECTOR',
}
export type CommandArgs = Array<SubCommand | string | number | object>;
enum Format {
RESP = 'resp',
JSON = 'json',
}
type RedisClient = ReturnType<typeof createClient>;
const toString = (s: string | number): string =>
typeof s === 'string' ? s : `${s}`;
export class Client extends EventEmitter {
private redis: RedisClient;
private redisConnecting?: Promise<void>;
private subscriber: RedisClient;
private subscriberConnecting?: Promise<void>;
private format: `${Format}` = Format.RESP;
constructor(url: string, options?: RedisClientOptions) {
super();
this.redis = createClient({ ...options, url })
.on('ready', () => {
this.format = Format.RESP;
})
.on('error', (error) => {
/* istanbul ignore next */
this.emit('error', error);
})
.on('end', () => {
this.format = Format.RESP;
});
this.subscriber = this.redis.duplicate().on('error', (error) => {
/* istanbul ignore next */
this.emit('error', error);
});
}
private connect(): Promise<void> {
if (typeof this.redisConnecting === 'undefined') {
this.redisConnecting = this.redis.connect();
}
return this.redisConnecting;
}
private connectSubscriber(): Promise<void> {
if (typeof this.subscriberConnecting === 'undefined') {
this.subscriberConnecting = this.subscriber.connect();
}
return this.subscriberConnecting;
}
private async rawCommand(
command: string,
args?: CommandArgs
): Promise<string> {
await this.connect();
return this.redis.sendCommand([command, ...(args || []).map(toString)]);
}
async command<R extends JSONResponse = JSONResponse>(
command: Command,
args?: CommandArgs
): Promise<R> {
await this.output('json');
const response = await this.rawCommand(command, args);
return parseResponse<R>(response);
}
private async output(format: `${Format}`): Promise<void> {
if (this.format === format) return;
const response = await this.rawCommand(Command.OUTPUT, [format]);
if (format === 'json') {
parseResponse(response);
}
this.format = format;
}
async subscribe(channels: string | string[]): Promise<void> {
await this.connectSubscriber();
return this.subscriber.subscribe(channels, (message, channel) =>
this.emit('message', JSON.parse(message), channel)
);
}
async pSubscribe(patterns: string | string[]): Promise<void> {
await this.connectSubscriber();
return this.subscriber.pSubscribe(patterns, (message, channel) =>
this.emit('message', JSON.parse(message), channel)
);
}
unsubscribe(channels: string | string[] = []): Promise<void> {
return this.subscriber.unsubscribe(channels);
}
pUnsubscribe(patterns: string | string[] = []): Promise<void> {
return this.subscriber.unsubscribe(patterns);
}
async quit(force = false): Promise<void> {
await Promise.all([this.redisConnecting, this.subscriberConnecting]);
if (force) {
await Promise.all([
this.redis.isOpen && this.redis.disconnect(),
this.subscriber.isOpen && this.subscriber.disconnect(),
]);
} else {
/**
* Issue with node-redis v4
* We have to put back output to resp otherwise quit will take forever
*/
await (this.redis.isOpen && this.output('resp'));
await Promise.all([
this.redis.isOpen && this.redis.quit(),
this.subscriber.isOpen && this.subscriber.quit(),
]);
}
delete this.redisConnecting;
delete this.subscriberConnecting;
}
}