1 | const { EventEmitter } = require('events');
|
2 | const Proto = require('uberproto');
|
3 |
|
4 |
|
5 |
|
6 | const eventHook = exports.eventHook = function eventHook () {
|
7 | return function (hook) {
|
8 | const { app, service } = hook;
|
9 | const eventName = hook.event === null ? hook.event : app.eventMappings[hook.method];
|
10 | const isHookEvent = service._hookEvents && service._hookEvents.indexOf(eventName) !== -1;
|
11 |
|
12 |
|
13 | if (eventName && isHookEvent && hook.type !== 'error') {
|
14 | const results = Array.isArray(hook.result) ? hook.result : [ hook.result ];
|
15 |
|
16 | results.forEach(element => service.emit(eventName, element, hook));
|
17 | }
|
18 | };
|
19 | };
|
20 |
|
21 |
|
22 | const eventMixin = exports.eventMixin = function eventMixin (service) {
|
23 | if (service._serviceEvents) {
|
24 | return;
|
25 | }
|
26 |
|
27 | const app = this;
|
28 |
|
29 | const isEmitter = typeof service.on === 'function' &&
|
30 | typeof service.emit === 'function';
|
31 |
|
32 |
|
33 | if (typeof service.mixin === 'function' && !isEmitter) {
|
34 | service.mixin(EventEmitter.prototype);
|
35 | }
|
36 |
|
37 |
|
38 | Object.defineProperties(service, {
|
39 |
|
40 | _serviceEvents: {
|
41 | value: Array.isArray(service.events) ? service.events.slice() : []
|
42 | },
|
43 |
|
44 |
|
45 | _hookEvents: {
|
46 | value: []
|
47 | }
|
48 | });
|
49 |
|
50 |
|
51 | Object.keys(app.eventMappings).forEach(method => {
|
52 | const event = app.eventMappings[method];
|
53 | const alreadyEmits = service._serviceEvents.indexOf(event) !== -1;
|
54 |
|
55 |
|
56 |
|
57 | if (typeof service[method] === 'function' && !alreadyEmits) {
|
58 | service._serviceEvents.push(event);
|
59 | service._hookEvents.push(event);
|
60 | }
|
61 | });
|
62 | };
|
63 |
|
64 | module.exports = function () {
|
65 | return function (app) {
|
66 |
|
67 | Object.assign(app, {
|
68 | eventMappings: {
|
69 | create: 'created',
|
70 | update: 'updated',
|
71 | remove: 'removed',
|
72 | patch: 'patched'
|
73 | }
|
74 | });
|
75 |
|
76 |
|
77 |
|
78 | app.hooks({ finally: eventHook() });
|
79 |
|
80 |
|
81 | Proto.mixin(EventEmitter.prototype, app);
|
82 |
|
83 | app.mixins.push(eventMixin);
|
84 | };
|
85 | };
|