-
Notifications
You must be signed in to change notification settings - Fork 13
/
redis_client.ts
239 lines (203 loc) · 5.82 KB
/
redis_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
227
228
229
230
231
232
233
234
235
236
237
238
239
import net from 'net';
import { RedisSerializer } from './redis_serializer';
import { RedisCommands } from './redis_commands';
import { RedisDeserializer } from './redis_deserializer';
import { Queue } from '../utils/queue';
interface IRedisClient {
/**
* The Redis Server host value.
* e.g.: '127.0.0.1'
*
* @type {string}
*/
host: string;
/**
* The Redis Server port.
* e.g.: 6789
*
* @type {number}
*/
port: number;
/**
* This function connects the client to the given host and port.
* It create a socket and assigns listens to various events such as
* 'close', 'connect', 'timeout', 'error', and 'data'.
*/
connect(): void;
/**
* This function closes the Socket to the server.
*/
disconnect(): void;
/**
* Sends the PING command to the Redis Server with optional message.
*
* @param {?string} [message] - Optional message in PING
*/
ping(message?: string): void;
/**
* Sends the SET command to the Redis server with given key and value
*
* @param {string} key
* @param {string} value
*/
set(key: string, value: string): void;
/**
* Sends the ECHO command to the Redis server with provided message.
*
* @param {string} message
*/
echo(message: string): void;
/**
* Sends the GET command to the Redis server.
* Waits for the server to return the value (if present) otherwise null.
*
* @param {string} key
* @returns {Promise<string | null>}
*/
get(key: string): Promise<string | null>;
/**
* Sends the DEL command to the Server.
* Waits for the server to respond with a number,
* representing the elements deleted in the delete operation.
*
* @param {string} key
* @returns {Promise<number>}
*/
delete(key: string): Promise<number>;
/**
* This function sets the timeout for the TCP Socket.
*
* @param {number} timeout
*/
setTimeout(timeout: number): void;
}
interface ICommandWaitingForReply {
resolve(reply?: unknown): void;
reject(reply?: unknown): void;
}
class CommandWaitingForReply {
resolve;
reject;
constructor(
resolve: (value: unknown) => void,
reject: (value: unknown) => void
) {
this.resolve = resolve;
this.reject = reject;
}
}
export class RedisClient implements IRedisClient {
host;
port;
private sock?: net.Socket;
private serializer = new RedisSerializer();
private commandsQueue: Queue<ICommandWaitingForReply>;
constructor(host: string = '127.0.0.1', port: number = 6379) {
this.host = host;
this.port = port;
this.commandsQueue = new Queue<ICommandWaitingForReply>(1000);
}
setTimeout(timeout: number): void {
if (this.sock) {
this.sock.setTimeout(timeout);
}
}
async connect(): Promise<void> {
this.sock = net.connect(this.port, this.host);
this.sock.setTimeout(30000);
this.sock.on('connect', () => {
console.log('Connected');
});
this.sock.on('timeout', () => {
console.error('Socket timeout');
this.sock?.end();
});
this.sock.on('error', (err) => {
console.error(err);
this.sock?.destroy();
});
this.sock.on('close', () => {
console.log('Connection Closed');
});
this.sock.on('data', (data) => {
const dataStr = data.toString();
const elem = this.commandsQueue.dequeue()!;
// Get the element from the queue.
try {
// Deserialize the response and resolve the Promise with the response.
const ans = new RedisDeserializer(dataStr).parse();
elem.resolve(ans);
} catch (err) {
// If some error occurred in Deserialization, then reject the Promise.
console.log(err);
if (err instanceof Error) {
elem.reject(err.message);
}
}
});
}
/**
* This function creates a Promise on which the client waits till the server responds to the command.
*
* @private
* @async
* @param {Array<string>} data
* @returns {Promise<unknown>}
*/
private async write(data: Array<string>): Promise<unknown> {
// Check if the Socket connection is open
if (this.sock && this.sock.readyState === 'open') {
// Creates a new Promise and appends to the queue.
// When the data is received from the server,
// the Promise is resolved or rejects based on the servers' response.
const newPromise = new Promise((res, rej) => {
const elem = new CommandWaitingForReply(res, rej);
this.commandsQueue.enqueue(elem);
});
// Write the serialized data in RESP format
this.sock.write(this.serializer.serialize(data, true));
return newPromise;
}
throw new Error('Connection is not established');
}
async disconnect() {
this.sock?.destroy();
}
async ping(message?: string): Promise<void> {
const data: string[] = [RedisCommands.PING];
if (message !== undefined) {
data.push(message);
}
console.log(await this.write(data));
}
async set(key: string, value: string): Promise<void> {
const data: string[] = [RedisCommands.SET, key, value];
console.log(await this.write(data));
}
async echo(message: string): Promise<void> {
const data: string[] = [RedisCommands.ECHO, message];
console.log(await this.write(data));
}
async get(key: string): Promise<string | null> {
const data: string[] = [RedisCommands.GET, key];
const response = await this.write(data);
if (typeof response === 'string' || response === null) {
return response;
}
if (response instanceof Error) {
throw response;
}
return null;
}
async delete(key: string): Promise<number> {
const data: string[] = [RedisCommands.DEL, key];
const response = await this.write(data);
if (typeof response === 'number') {
return response;
}
if (response instanceof Error) {
throw response;
}
throw 0;
}
}