-
Notifications
You must be signed in to change notification settings - Fork 3
/
Client.ts
206 lines (178 loc) · 5.2 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
import EventEmitter from 'events';
import { Redis, RedisOptions } from 'ioredis';
import { forwardEvents } from './events';
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 ConstructorArgs = (string | number | RedisOptions | undefined)[];
export type CommandArgs = Array<SubCommand | string | number | object>;
enum Format {
RESP = 'resp',
JSON = 'json',
}
const toString = (s: string | number): string =>
typeof s === 'string' ? s : `${s}`;
const applyDefaults = (args: ConstructorArgs) => {
const options = args.find((arg) => typeof arg === 'object');
if (!options) return [...args, { port: 9851, lazyConnect: true }];
return args.map((arg) =>
typeof arg === 'object'
? { port: 9851, ...arg, lazyConnect: true }
: arg
);
};
const catchConnectionClosed = (error: Error) => {
if (error.message !== 'Connection is closed.') throw error;
};
export class Client extends EventEmitter {
private redis: Redis;
private subscriber: Redis;
private format: `${Format}` = Format.RESP;
constructor(...args: ConstructorArgs) {
super();
this.redis = new Redis(...(applyDefaults(args) as [string]))
.on('ready', () => {
this.format = Format.RESP;
})
.on('end', () => {
this.format = Format.RESP;
});
forwardEvents(this.redis, this);
this.subscriber = this.redis
.duplicate()
.on('error', (error) =>
/* istanbul ignore next */
this.emit('error', error)
)
.on('message', (channel, message) =>
this.emit('message', JSON.parse(message), channel)
)
.on('pmessage', (pattern, channel, message) =>
this.emit('message', JSON.parse(message), channel, pattern)
);
}
private async rawCommand(
command: string,
args?: CommandArgs
): Promise<string> {
return this.redis.call(
command,
...(args || []).map(toString)
) as Promise<string>;
}
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.subscriber.subscribe(...channels);
}
async pSubscribe(patterns: string | string[]): Promise<void> {
await this.subscriber.psubscribe(...patterns);
}
async unsubscribe(...channels: string[]): Promise<void> {
await this.subscriber.unsubscribe(...channels);
}
async pUnsubscribe(...patterns: string[]): Promise<void> {
await this.subscriber.punsubscribe(...patterns);
}
async quit(force = false): Promise<void> {
await Promise.all(
force
? [this.redis.disconnect(), this.subscriber.disconnect()]
: [
this.redis.quit().catch(catchConnectionClosed),
this.subscriber.quit().catch(catchConnectionClosed),
]
);
}
}