-
Notifications
You must be signed in to change notification settings - Fork 417
/
index.ts
62 lines (50 loc) · 1.34 KB
/
index.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
/**
* Load redis lua scripts.
* The name of the script must have the following format:
*
* cmdName-numKeys.lua
*
* cmdName must be in camel case format.
*
* For example:
* moveToFinish-3.lua
*
*/
'use strict';
import IORedis from 'ioredis';
const path = require('path');
const util = require('util');
const fs = require('fs');
const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);
interface Command {
name: string;
options: {
numberOfKeys: number;
lua: string;
};
}
export const load = async function(client: IORedis.Redis) {
const scripts = await loadScripts(__dirname);
scripts.forEach((command: Command) => {
client.defineCommand(command.name, command.options);
});
};
async function loadScripts(dir: string): Promise<Command[]> {
const files = await readdir(dir);
const commands = await Promise.all<Command>(
files
.filter((file: string) => path.extname(file) === '.lua')
.map(async (file: string) => {
const longName = path.basename(file, '.lua');
const name = longName.split('-')[0];
const numberOfKeys = parseInt(longName.split('-')[1]);
const lua = await readFile(path.join(dir, file));
return {
name,
options: { numberOfKeys, lua: lua.toString() },
};
}),
);
return commands;
}