-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathscript.ts
59 lines (52 loc) · 1.53 KB
/
script.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
import { createHash } from "crypto";
import { isPromise } from "./promiseContainer";
import Command from "./command";
import asCallback from "standard-as-callback";
import { CallbackFunction } from "./types";
export default class Script {
private sha: string;
constructor(
private lua: string,
private numberOfKeys: number = null,
private keyPrefix: string = "",
private readOnly: boolean = false
) {
this.sha = createHash("sha1").update(lua).digest("hex");
}
execute(
container: any,
args: any[],
options: any,
callback?: CallbackFunction
) {
if (typeof this.numberOfKeys === "number") {
args.unshift(this.numberOfKeys);
}
if (this.keyPrefix) {
options.keyPrefix = this.keyPrefix;
}
if (this.readOnly) {
options.readOnly = true;
}
const evalsha = new Command("evalsha", [this.sha].concat(args), options);
evalsha.isCustomCommand = true;
const result = container.sendCommand(evalsha);
if (isPromise(result)) {
return asCallback(
result.catch((err: Error) => {
if (err.toString().indexOf("NOSCRIPT") === -1) {
throw err;
}
return container.sendCommand(
new Command("eval", [this.lua].concat(args), options)
);
}),
callback
);
}
// result is not a Promise--probably returned from a pipeline chain; however,
// we still need the callback to fire when the script is evaluated
asCallback(evalsha.promise, callback);
return result;
}
}