1 | import { NextFunction, EventEmitter } from './dependencies';
|
2 | import { HookContext, FeathersService } from './declarations';
|
3 | import { getServiceOptions, defaultEventMap } from './service';
|
4 |
|
5 | export function eventHook (context: HookContext, next: NextFunction) {
|
6 | const { events } = getServiceOptions((context as any).self);
|
7 | const defaultEvent = (defaultEventMap as any)[context.method] || null;
|
8 |
|
9 | context.event = defaultEvent;
|
10 |
|
11 | return next().then(() => {
|
12 |
|
13 |
|
14 | if (typeof context.event === 'string' && !events.includes(context.event)) {
|
15 | const results = Array.isArray(context.result) ? context.result : [ context.result ];
|
16 |
|
17 | results.forEach(element => (context as any).self.emit(context.event, element, context));
|
18 | }
|
19 | });
|
20 | }
|
21 |
|
22 | export function eventMixin<A> (service: FeathersService<A>) {
|
23 | const isEmitter = typeof service.on === 'function' &&
|
24 | typeof service.emit === 'function';
|
25 |
|
26 | if (!isEmitter) {
|
27 | Object.assign(service, EventEmitter.prototype);
|
28 | }
|
29 |
|
30 | return service;
|
31 | }
|