UNPKG

1.08 kBJavaScriptView Raw
1/* @flow */
2import { createClient, RedisClientType } from './redis-client';
3
4import type { CommitConfig } from '../types/Config.type';
5import runLua from './runLua';
6
7const queryLua = `
8local from = tonumber(ARGV[1]);
9local to = tonumber(ARGV[2]) or redis.call('HLEN', KEYS[1]);
10local newArray = {};
11
12for id=from,to do
13 table.insert(newArray, {id, redis.call('hget', KEYS[1], id)});
14end
15
16return newArray
17`;
18
19export 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
31export 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 // we trust the input from commit. otherwise we have to do a try-parse
39 return events;
40 };
41};