UNPKG

1.19 kBPlain TextView Raw
1import { NextFunction, EventEmitter } from './dependencies';
2import { HookContext, FeathersService } from './declarations';
3import { getServiceOptions, defaultEventMap } from './service';
4
5export 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 // Send the event only if the service does not do so already (indicated in the `events` option)
13 // This is used for custom events and for client services receiving event from the server
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
22export 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}