1 |
|
2 | import { createClient, RedisClientType } from './redis-client';
|
3 |
|
4 | import type { CommitConfig } from '../types/Config.type';
|
5 | import runLua from './runLua';
|
6 |
|
7 | const queryLua = `
|
8 | local from = tonumber(ARGV[1]);
|
9 | local to = tonumber(ARGV[2]) or redis.call('HLEN', KEYS[1]);
|
10 | local newArray = {};
|
11 |
|
12 | for id=from,to do
|
13 | table.insert(newArray, {id, redis.call('hget', KEYS[1], id)});
|
14 | end
|
15 |
|
16 | return newArray
|
17 | `;
|
18 |
|
19 | export const query = async (client: RedisClientType, namespc: string, ...argv: number[]) => {
|
20 | const array = await runLua(client, queryLua, {
|
21 | keys: [`${namespc}::events`],
|
22 | argv: argv.map(String),
|
23 | });
|
24 |
|
25 | return array.map(([id, event]) => ({
|
26 | id,
|
27 | ...JSON.parse(event),
|
28 | }));
|
29 | };
|
30 |
|
31 | export default (config: CommitConfig) => {
|
32 | const client = createClient(config.redis);
|
33 |
|
34 | return async (req: any) => {
|
35 | const lastEventId = Number(req.headers['Last-Event-ID'] || req.query.lastEventId);
|
36 | const events = await query(client, config.namespc, lastEventId);
|
37 |
|
38 |
|
39 | return events;
|
40 | };
|
41 | };
|