UNPKG

1.08 kBJavaScriptView Raw
1/* @flow */
2import promisify from 'es6-promisify';
3import crypto from 'crypto';
4
5type EvalParams = {
6 keys: ?(string[]),
7 argv: ?(string[]),
8};
9
10type RunLua = (any, string, EvalParams) => Promise<any>;
11
12const sha1 = (text: string): string => {
13 const hash = crypto.createHash('sha1');
14 return hash.update(text).digest('hex');
15};
16
17const map = new Map();
18
19const runLua: RunLua = promisify(
20 (redisClient, luaScript: string, { keys, argv }: EvalParams, cb) => {
21 const nonEmptyKeys = keys || [];
22 const nonEmptyArgv = argv || [];
23
24 const hashOrNull = map.get(luaScript);
25 if (hashOrNull) {
26 return redisClient.evalsha(
27 hashOrNull,
28 nonEmptyKeys.length,
29 ...nonEmptyKeys,
30 ...nonEmptyArgv,
31 cb
32 );
33 }
34
35 return redisClient.eval(
36 luaScript,
37 nonEmptyKeys.length,
38 ...nonEmptyKeys,
39 ...nonEmptyArgv,
40 (err, val) => {
41 if (!err) {
42 const hash = sha1(luaScript);
43 map.set(luaScript, hash);
44 }
45
46 cb(err, val);
47 }
48 );
49 }
50);
51
52export default runLua;