遇到这个问题,花了一天时间试图找出一个好的答案。这可能并不适合所有用例,但我能够在 Nest 的核心包中复制一个通用模式以满足我的需求。
我想创建自己的装饰器来注释控制器方法以处理事件(例如,@Subscribe('some.topic.key') async handler() { ... }))。
为了实现这一点,我的装饰器使用来自@nestjs/common 的SetMetadata 来注册一些我需要的元数据(它被应用到的方法名称、它所属的类、对该方法的引用)。
export const Subscribe = (topic: string) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
SetMetadata<string, RabbitSubscriberMetadataConfiguration>(
RABBITMQ_SUBSCRIBER,
{
topic,
target: target.constructor.name,
methodName: propertyKey,
callback: descriptor.value,
},
)(target, propertyKey, descriptor);
};
};
从那里,我能够创建自己的模块,该模块与 Nest 的生命周期钩子挂钩,以查找我用我的装饰器装饰的所有方法,并对其应用一些逻辑,例如:
@Module({
imports: [RabbitmqChannelProvider],
providers: [RabbitmqService, MetadataScanner, RabbitmqSubscriberExplorer],
exports: [RabbitmqService],
})
export class RabbitmqModule implements OnModuleInit {
constructor(
private readonly explorer: RabbitmqSubscriberExplorer,
private readonly rabbitmqService: RabbitmqService,
) {}
async onModuleInit() {
// find everything marked with @Subscribe
const subscribers = this.explorer.explore();
// set up subscriptions
for (const subscriber of subscribers) {
await this.rabbitmqService.subscribe(
subscriber.topic,
subscriber.callback,
);
}
}
}
资源管理器服务使用@nestjs/core 中的一些实用程序来内省容器并处理查找所有带有元数据的修饰函数。
@Injectable()
export class RabbitmqSubscriberExplorer {
constructor(
private readonly modulesContainer: ModulesContainer,
private readonly metadataScanner: MetadataScanner,
) {}
public explore(): RabbitSubscriberMetadataConfiguration[] {
// find all the controllers
const modules = [...this.modulesContainer.values()];
const controllersMap = modules
.filter(({ controllers }) => controllers.size > 0)
.map(({ controllers }) => controllers);
// munge the instance wrappers into a nice format
const instanceWrappers: InstanceWrapper<Controller>[] = [];
controllersMap.forEach(map => {
const mapKeys = [...map.keys()];
instanceWrappers.push(
...mapKeys.map(key => {
return map.get(key);
}),
);
});
// find the handlers marked with @Subscribe
return instanceWrappers
.map(({ instance }) => {
const instancePrototype = Object.getPrototypeOf(instance);
return this.metadataScanner.scanFromPrototype(
instance,
instancePrototype,
method =>
this.exploreMethodMetadata(instance, instancePrototype, method),
);
})
.reduce((prev, curr) => {
return prev.concat(curr);
});
}
public exploreMethodMetadata(
instance: object,
instancePrototype: Controller,
methodKey: string,
): RabbitSubscriberMetadataConfiguration | null {
const targetCallback = instancePrototype[methodKey];
const handler = Reflect.getMetadata(RABBITMQ_SUBSCRIBER, targetCallback);
if (handler == null) {
return null;
}
return handler;
}
}
我并不认为这是处理此问题的最佳方法,但它对我来说效果很好。使用此代码需要您自担风险,它应该可以帮助您入门:-)。我改编了这里提供的代码:https://github.com/nestjs/nest/blob/5.1.0-stable/packages/microservices/listener-metadata-explorer.ts