-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathmock.js
executable file
·130 lines (91 loc) · 2.99 KB
/
mock.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
'use strict';
// Adapted from https://github.com/luin/ioredis
// Copyright (c) 2015-2019 Zihua Li - MIT Licensed
const EventEmitter = require('events').EventEmitter;
const Net = require('net');
const Parser = require('redis-parser');
const internals = {};
module.exports = internals.MockServer = class extends EventEmitter {
constructor(port, handler) {
super();
this.REDIS_OK = '+OK';
this.port = port;
this.handler = handler;
this.connect();
}
connect() {
this.socket = Net.createServer();
this.socket.on('connection', (socket) => {
process.nextTick(() => this.emit('connect', socket));
const parser = new Parser({
returnBuffers: true,
returnReply: (reply) => {
reply = this.convertBufferToString(reply);
this.write(socket, this.handler?.(reply));
},
returnError: function () {}
});
socket.on('end', function () {
this.emit('disconnect', socket);
});
socket.on('data', (data) => {
parser.execute(data);
});
});
this.socket.listen(this.port);
}
write(c, input) {
const convert = function (str, data) {
let result;
if (typeof data === 'undefined') {
data = internals.MockServer.REDIS_OK;
}
if (data === internals.MockServer.REDIS_OK) {
result = '+OK\r\n';
}
else if (data instanceof Error) {
result = '-' + data.message + '\r\n';
}
else if (Array.isArray(data)) {
result = '*' + data.length + '\r\n';
data.forEach((item) => {
result += convert(str, item);
});
}
else if (typeof data === 'number') {
result = ':' + data + '\r\n';
}
else if (data === null) {
result = '$-1\r\n';
}
else {
data = data.toString();
result = '$' + data.length + '\r\n';
result += data + '\r\n';
}
return str + result;
};
if (c.writable) {
c.write(convert('', input));
}
}
convertBufferToString(value, encoding) {
if (value instanceof Buffer) {
return value.toString(encoding);
}
if (Array.isArray(value)) {
const length = value.length;
const res = Array(length);
for (let i = 0; i < length; ++i) {
res[i] = value[i] instanceof Buffer && encoding === 'utf8'
? value[i].toString()
: this.convertBufferToString(value[i], encoding);
}
return res;
}
return value;
}
disconnect() {
this.socket.close();
}
};