-
Notifications
You must be signed in to change notification settings - Fork 34
/
event-subscribers.loader.ts
193 lines (172 loc) 路 5.54 KB
/
event-subscribers.loader.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnApplicationShutdown,
} from '@nestjs/common';
import {
ContextIdFactory,
DiscoveryService,
MetadataScanner,
ModuleRef,
} from '@nestjs/core';
import { Injector } from '@nestjs/core/injector/injector';
import {
ContextId,
InstanceWrapper,
} from '@nestjs/core/injector/instance-wrapper';
import { Module } from '@nestjs/core/injector/module';
import { EventEmitter2 } from 'eventemitter2';
import { EventsMetadataAccessor } from './events-metadata.accessor';
import { OnEventOptions } from './interfaces';
@Injectable()
export class EventSubscribersLoader
implements OnApplicationBootstrap, OnApplicationShutdown
{
private readonly injector = new Injector();
private readonly logger = new Logger('Event');
constructor(
private readonly discoveryService: DiscoveryService,
private readonly eventEmitter: EventEmitter2,
private readonly metadataAccessor: EventsMetadataAccessor,
private readonly metadataScanner: MetadataScanner,
private readonly moduleRef: ModuleRef,
) {}
onApplicationBootstrap() {
this.loadEventListeners();
}
onApplicationShutdown() {
this.eventEmitter.removeAllListeners();
}
loadEventListeners() {
const providers = this.discoveryService.getProviders();
const controllers = this.discoveryService.getControllers();
[...providers, ...controllers]
.filter(wrapper => wrapper.instance && !wrapper.isAlias)
.forEach((wrapper: InstanceWrapper) => {
const { instance } = wrapper;
const prototype = Object.getPrototypeOf(instance) || {};
const isRequestScoped = !wrapper.isDependencyTreeStatic();
this.metadataScanner.scanFromPrototype(
instance,
prototype,
(methodKey: string) =>
this.subscribeToEventIfListener(
instance,
methodKey,
isRequestScoped,
wrapper.host as Module,
),
);
});
}
private subscribeToEventIfListener(
instance: Record<string, any>,
methodKey: string,
isRequestScoped: boolean,
moduleRef: Module,
) {
const eventListenerMetadatas =
this.metadataAccessor.getEventHandlerMetadata(instance[methodKey]);
if (!eventListenerMetadatas) {
return;
}
for (const eventListenerMetadata of eventListenerMetadatas) {
const { event, options } = eventListenerMetadata;
const listenerMethod = this.getRegisterListenerMethodBasedOn(options);
if (isRequestScoped) {
this.registerRequestScopedListener({
event,
eventListenerInstance: instance,
listenerMethod,
listenerMethodKey: methodKey,
moduleRef,
options,
});
} else {
listenerMethod(
event,
(...args: unknown[]) =>
this.wrapFunctionInTryCatchBlocks(instance, methodKey, args, options),
options,
);
}
}
}
private getRegisterListenerMethodBasedOn(options?: OnEventOptions) {
return Boolean(options?.prependListener)
? this.eventEmitter.prependListener.bind(this.eventEmitter)
: this.eventEmitter.on.bind(this.eventEmitter);
}
private registerRequestScopedListener(eventListenerContext: {
listenerMethod: EventEmitter2['on'];
event: string | symbol | (string | symbol)[];
eventListenerInstance: Record<string, any>;
moduleRef: Module;
listenerMethodKey: string;
options?: OnEventOptions;
}) {
const {
listenerMethod,
event,
eventListenerInstance,
moduleRef,
listenerMethodKey,
options,
} = eventListenerContext;
listenerMethod(
event,
async (...args: unknown[]) => {
const contextId = ContextIdFactory.create();
this.registerEventPayloadByContextId(args, contextId);
const contextInstance = await this.injector.loadPerContext(
eventListenerInstance,
moduleRef,
moduleRef.providers,
contextId,
);
return this.wrapFunctionInTryCatchBlocks(
contextInstance,
listenerMethodKey,
args,
options,
);
},
options,
);
}
private registerEventPayloadByContextId(
eventPayload: unknown[],
contextId: ContextId,
) {
/*
**Required explanation for the ternary below**
We need the conditional below because an event can be emitted with a variable amount of arguments.
For instance, we can do `this.eventEmitter.emit('event', 'payload1', 'payload2', ..., 'payloadN');`
All payload arguments are internally stored as an array. So, imagine we emitted an event as follows:
`this.eventEmitter.emit('event', 'payload');
if we registered the original `eventPayload`, when we try to inject it in a listener, it'll be retrieved as [`payload`].
However, whoever is using this library would certainly expect the event payload to be a single string 'payload', not an array,
since this is what we emitted above.
*/
const payloadObjectOrArray =
eventPayload.length > 1 ? eventPayload : eventPayload[0];
this.moduleRef.registerRequestByContextId(payloadObjectOrArray, contextId);
}
private async wrapFunctionInTryCatchBlocks(
instance: Record<string, any>,
methodKey: string,
args: unknown[],
options?: OnEventOptions,
) {
try {
return await instance[methodKey].call(instance, ...args);
} catch (e) {
if (options?.suppressErrors ?? true) {
this.logger.error(e);
} else {
throw e;
}
}
}
}