-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJobs.ts
66 lines (53 loc) · 1.65 KB
/
Jobs.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
63
64
65
66
import Queue from './Queue';
import Handler from './Handler';
import EventHandlerMapper from './EventHandlerMapper';
import type { HandlerFunction } from '../types/common';
class Jobs<
IHandler extends {
[key: string]: HandlerFunction;
},
IEventHandlerMapper extends { [key: string]: Array<keyof IHandler> }
> {
private _handlers: Handler<IHandler>;
private _eventHandlerMapper: EventHandlerMapper<IEventHandlerMapper>;
public constructor(
handlers: Handler<IHandler>,
eventHandlerMapper: EventHandlerMapper<IEventHandlerMapper>
) {
this._handlers = handlers;
this._eventHandlerMapper = eventHandlerMapper;
}
get instance() {
return this;
}
public get handlers() {
return this._handlers.keys;
}
public get events() {
return this._eventHandlerMapper.keys;
}
public getHandlerFunctions(event: keyof IEventHandlerMapper) {
return this._eventHandlerMapper.eventHandlerMapper[event];
}
public async trigger(eventName: keyof IEventHandlerMapper, parameters: any) {
const functions = this.getHandlerFunctions(eventName);
if (!functions) {
throw new Error(
`No handler function found for event: '${String(eventName)}'`
);
}
return await Promise.all(
functions.map((handlerKey) => {
return Queue.add({ scope: handlerKey as string, data: parameters });
})
);
}
public dispatch(handlerKey: keyof IHandler, parameters: any = {}) {
const handler = this._handlers.handlers[handlerKey];
if (!handler) {
throw new Error(`No function found for handler: '${String(handlerKey)}`);
}
return handler(parameters);
}
}
export default Jobs;