-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.ts
68 lines (60 loc) · 1.84 KB
/
handler.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
import {
RedisArray,
RedisValue,
stringToBuffer,
bufferToString,
RedisValueOf
} from "./protocol.ts";
import { RedisClient } from "./client.ts";
export interface RedisHandler {
onRequest(request: RedisArray): Promise<RedisValue>;
onConnCreated(client: RedisClient): void;
onConnExit(client: RedisClient): void;
}
export class BaseHandler implements RedisHandler {
clients: RedisClient[] = [];
public onConnCreated(client: RedisClient) {
this.clients = [client, ...this.clients];
}
public onConnExit(client: RedisClient) {
this.clients = this.clients.filter(c => c !== client);
}
private async command_INFO(request: RedisArray): Promise<RedisValue> {
return RedisValueOf.array([
`# Tiny Redis`,
`Deno v${JSON.stringify(Deno.version)}`,
"",
`# Clients`,
`Connected: ${this.clients.length}`,
""
]);
}
private async command_COMMAND(request: RedisArray): Promise<RedisValue> {
const cmds = Object.keys(this.commands);
return RedisValueOf.array([...cmds, ...Object.keys(this._commands)]);
}
_commands: { [index: string]: any } = {
"COMMAND": this.command_COMMAND,
"INFO": this.command_INFO
};
commands: { [index: string]: any } = {};
public async onRequest(request: RedisArray): Promise<RedisValue> {
const command = request.value[0];
if (command.tag !== "RedisString" && command.tag !== "RedisBulkString") {
return {
tag: "RedisError",
value: stringToBuffer(`Command Invlid: ${JSON.stringify(request)}`)
};
}
const cmd = bufferToString(command.value).toUpperCase();
const h = this.commands[cmd] || this._commands[cmd];
if (h) {
return h.bind(this)(request) as RedisValue;
} else {
return {
tag: "RedisError",
value: stringToBuffer(`Command unimplemented: ${cmd}`)
};
}
}
}