nestjs-metadata-discovery
v0.1.2
Published
<p align="center"> <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a> </p>
Downloads
15
Readme
NestJS Metadata Discovery Module
Description
A NestJS Module that simplifies the creation of services that can discover metadata from methods to be consumed by decorated handlers from other classes.
Installation
pnpm nestjs-metadata-discovery@latestUsage
Create a service that implements
registerHandler. Here we have an example of a class that extendsEventEmitterthat listens for events and calls the handler that was registered in theService1class.@Injectable() export class Service1 extends EventEmitter { @Inject('OPTIONS') private options: any; // Map of handlers to the tuple of Context and Decorated Method private map_of_handlers = new Map<string, [any, FunctionController]>(); constructor() { super(); // Listen for Some Events this.on('SOME_EVENT', this.handleSomeEvent.bind(this)); } // Catch all Handler async handleSomeEvent(...args) { // Get handler from map of registered handlers const handler = this.map_of_handlers.get(metadata_value); if (!handler) { throw new Error('Handler not found'); } const [context, method] = handler; // Call handler in the context of the class where it was defined. return method.apply(context, args); } registerHander( metadata_key: string, metadata_value: string, handler: FunctionConstructor, instance: any ) { // Register handler to map of registered handlers this.map_of_handlers.set(metadata_value, [instance, handler]); } }Create a decorator that will be used to decorate the method that will be called when the event is emitted.
export function Handle(some_key: string) { return applyDecorators(SetMetadata('EVENT_HANDLER', some_key)); }Decorate your
Service Methodswith your decorator.@Injectable() export class Service2 { @Handle('SOME_EVENT') async handleSomeEvent(...args) { // Do something } }Use the
MetadataDiscoveryModuleto register your handlers.import { MetadataDiscoveryModule } from '@app/metadata-discovery'; @Module({ imports: [ MetadataDiscoveryModule.forRoot( { metadata_key: 'EVENT_HANDLER', // Metadata Key to discover discover_controllers: true, // Discover Controllers discover_services: true, // Discover Services }, Service1 // Service that implements `registerHandler` ), // Import other modules ], providers: [ // Import other providers, Service2, ], }) export class AppModule {}When the app runs and
SOME_EVENTSevents are emitted, theService1will call the methods decorated inService2.
