-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipeline.ts
More file actions
76 lines (65 loc) · 1.52 KB
/
pipeline.ts
File metadata and controls
76 lines (65 loc) · 1.52 KB
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
import type { Connection } from "./connection.ts";
import { CommandExecutor } from "./executor.ts";
import {
okReply,
RawOrError,
RedisReply,
RedisValue,
sendCommands,
} from "./protocol/mod.ts";
import { create, Redis } from "./redis.ts";
export interface RedisPipeline extends Redis {
flush(): Promise<RawOrError[]>;
}
export function createRedisPipeline(
connection: Connection,
tx = false,
): RedisPipeline {
const executor = new PipelineExecutor(connection, tx);
const client = create(executor);
return Object.assign(client, {
flush: () => executor.flush(),
});
}
interface QueuedCommand {
command: string;
args: RedisValue[];
}
export class PipelineExecutor implements CommandExecutor {
private commands: QueuedCommand[] = [];
constructor(
readonly connection: Connection,
private tx: boolean,
) {}
exec(command: string, ...args: RedisValue[]): Promise<RedisReply> {
this.commands.push({ command, args });
return Promise.resolve(okReply);
}
close(): void {
this.connection.close();
}
async flush(): Promise<RawOrError[]> {
let commandsToFlush: QueuedCommand[] = [...this.commands];
this.commands = [];
if (this.tx) {
commandsToFlush = [
{ command: "MULTI", args: [] },
...commandsToFlush,
{ command: "EXEC", args: [] },
];
}
if (commandsToFlush.length === 0) {
return [];
}
try {
const replies = await sendCommands(
this.connection.writer,
this.connection.reader,
commandsToFlush,
);
return replies;
} catch (error) {
throw error;
}
}
}