-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
listener-metadata-explorer.ts
91 lines (84 loc) · 2.71 KB
/
listener-metadata-explorer.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
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { isFunction, isUndefined } from '@nestjs/common/utils/shared.utils';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import {
CLIENT_CONFIGURATION_METADATA,
CLIENT_METADATA,
PATTERN_EXTRAS_METADATA,
PATTERN_HANDLER_METADATA,
PATTERN_METADATA,
TRANSPORT_METADATA,
} from './constants';
import { Transport } from './enums';
import { PatternHandler } from './enums/pattern-handler.enum';
import { ClientOptions, PatternMetadata } from './interfaces';
export interface ClientProperties {
property: string;
metadata: ClientOptions;
}
export interface EventOrMessageListenerDefinition {
patterns: PatternMetadata[];
methodKey: string;
isEventHandler: boolean;
targetCallback: (...args: any[]) => any;
transport?: Transport;
extras?: Record<string, any>;
}
export interface MessageRequestProperties {
requestPattern: PatternMetadata;
replyPattern: PatternMetadata;
}
export class ListenerMetadataExplorer {
constructor(private readonly metadataScanner: MetadataScanner) {}
public explore(instance: Controller): EventOrMessageListenerDefinition[] {
const instancePrototype = Object.getPrototypeOf(instance);
return this.metadataScanner
.getAllMethodNames(instancePrototype)
.map(method => this.exploreMethodMetadata(instancePrototype, method))
.filter(metadata => metadata);
}
public exploreMethodMetadata(
instancePrototype: object,
methodKey: string,
): EventOrMessageListenerDefinition {
const targetCallback = instancePrototype[methodKey];
const handlerType = Reflect.getMetadata(
PATTERN_HANDLER_METADATA,
targetCallback,
);
if (isUndefined(handlerType)) {
return;
}
const patterns = Reflect.getMetadata(PATTERN_METADATA, targetCallback);
const transport = Reflect.getMetadata(TRANSPORT_METADATA, targetCallback);
const extras = Reflect.getMetadata(PATTERN_EXTRAS_METADATA, targetCallback);
return {
methodKey,
targetCallback,
patterns,
transport,
extras,
isEventHandler: handlerType === PatternHandler.EVENT,
};
}
public *scanForClientHooks(
instance: Controller,
): IterableIterator<ClientProperties> {
for (const propertyKey in instance) {
if (isFunction(propertyKey)) {
continue;
}
const property = String(propertyKey);
const isClient = Reflect.getMetadata(CLIENT_METADATA, instance, property);
if (isUndefined(isClient)) {
continue;
}
const metadata = Reflect.getMetadata(
CLIENT_CONFIGURATION_METADATA,
instance,
property,
);
yield { property, metadata };
}
}
}