-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathmulti-command.ts
95 lines (80 loc) · 3.13 KB
/
multi-command.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
import { fCallArguments } from './commander';
import { RedisCommand, RedisCommandArguments, RedisCommandRawReply, RedisFunction, RedisScript } from './commands';
import { ErrorReply, MultiErrorReply, WatchError } from './errors';
export interface RedisMultiQueuedCommand {
args: RedisCommandArguments;
transformReply?: RedisCommand['transformReply'];
}
export default class RedisMultiCommand {
static generateChainId(): symbol {
return Symbol('RedisMultiCommand Chain Id');
}
readonly queue: Array<RedisMultiQueuedCommand> = [];
readonly scriptsInUse = new Set<string>();
addCommand(args: RedisCommandArguments, transformReply?: RedisCommand['transformReply']): void {
this.queue.push({
args,
transformReply
});
}
addFunction(name: string, fn: RedisFunction, args: Array<unknown>): RedisCommandArguments {
const transformedArguments = fCallArguments(
name,
fn,
fn.transformArguments(...args)
);
this.queue.push({
args: transformedArguments,
transformReply: fn.transformReply
});
return transformedArguments;
}
addScript(script: RedisScript, args: Array<unknown>): RedisCommandArguments {
const transformedArguments: RedisCommandArguments = [];
if (this.scriptsInUse.has(script.SHA1)) {
transformedArguments.push(
'EVALSHA',
script.SHA1
);
} else {
this.scriptsInUse.add(script.SHA1);
transformedArguments.push(
'EVAL',
script.SCRIPT
);
}
if (script.NUMBER_OF_KEYS !== undefined) {
transformedArguments.push(script.NUMBER_OF_KEYS.toString());
}
const scriptArguments = script.transformArguments(...args);
transformedArguments.push(...scriptArguments);
if (scriptArguments.preserve) {
transformedArguments.preserve = scriptArguments.preserve;
}
this.addCommand(
transformedArguments,
script.transformReply
);
return transformedArguments;
}
handleExecReplies(rawReplies: Array<RedisCommandRawReply | ErrorReply>): Array<RedisCommandRawReply> {
const execReply = rawReplies[rawReplies.length - 1] as (null | Array<RedisCommandRawReply>);
if (execReply === null) {
throw new WatchError();
}
return this.transformReplies(execReply);
}
transformReplies(rawReplies: Array<RedisCommandRawReply | ErrorReply>): Array<RedisCommandRawReply> {
const errorIndexes: Array<number> = [],
replies = rawReplies.map((reply, i) => {
if (reply instanceof ErrorReply) {
errorIndexes.push(i);
return reply;
}
const { transformReply, args } = this.queue[i];
return transformReply ? transformReply(reply, args.preserve) : reply;
});
if (errorIndexes.length) throw new MultiErrorReply(replies, errorIndexes);
return replies;
}
}