-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.ts
51 lines (43 loc) · 1.26 KB
/
executor.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
import type { RedisReply, RedisValue } from './protocol/types.ts';
interface RedisFetchResponse {
error: boolean;
result: string;
}
export interface CommandExecutor {
exec(command: string, ...args: RedisValue[]): Promise<RedisReply>;
}
export class FetchCommandExecutor implements CommandExecutor {
private readonly url: string;
constructor(url: string) {
this.url = url;
}
exec(command: string, ...args: RedisValue[]): Promise<RedisReply> {
return this.sendCommand(command, args);
}
private sendCommand(command: string, args?: RedisValue[]) {
const payload = { command: [command, ...(args?.map((a) => String(a)) ?? [])].join(' ') };
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
};
return fetch(this.url, options)
.then((res) => res.json())
.then((json: RedisFetchResponse) => {
if (json.error) {
throw new Error(json.result);
}
return {
value() {
return json.result;
},
string() {
return String(json.result);
},
buffer() {
return new TextEncoder().encode(json.result);
}
} as RedisReply;
});
}
}