forked from cyx/redic.js
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmock.js
42 lines (27 loc) · 872 Bytes
/
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
const net = require('net');
const hiredis = require('hiredis');
const reader = new hiredis.Reader();
function create(commands) {
const server = net.createServer(function(socket) {
socket.on('data', function(data) {
reader.feed(data);
const buffer = reader.get();
const command = buffer[0].toLowerCase();
const args = buffer.slice(1);
if (!commands[command])
throw new Error('Command not registered: ' + command);
const res = reply(commands[command].apply(socket, args));
try {
socket.write(res);
} catch (ex) { }
});
});
return server;
}
function reply(obj) {
if (obj.constructor === String)
return '$' + obj.length + '\r\n' + obj + '\r\n';
if (obj.constructor === Array)
return '*' + obj.length + '\r\n' + obj.map(reply).join('');
}
module.exports = create;