@logistically/events-nestjs
Version:
NestJS integration for @logistically/events v3 - Event-driven architecture with Redis Streams
47 lines (46 loc) • 1.96 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AUTO_REGISTER_EVENTS_METADATA = void 0;
exports.AutoEvents = AutoEvents;
const common_1 = require("@nestjs/common");
exports.AUTO_REGISTER_EVENTS_METADATA = 'auto_register_events';
/**
* Decorator to mark a service for automatic event handler registration
* This will automatically discover and register all @AutoEventHandler methods
*
* USAGE:
* @Injectable()
* @AutoEvents()
* export class MyService {
* // No need to implement OnModuleInit!
* // The decorator handles everything automatically
* }
*/
function AutoEvents(options = { enabled: true }) {
return function (target) {
// Set the metadata
(0, common_1.SetMetadata)(exports.AUTO_REGISTER_EVENTS_METADATA, options)(target);
// Store the original onModuleInit method if it exists
const originalOnModuleInit = target.prototype.onModuleInit;
// Override onModuleInit to auto-register the service
target.prototype.onModuleInit = async function (...args) {
// Call the original onModuleInit if it exists
if (originalOnModuleInit) {
await originalOnModuleInit.apply(this, args);
}
// Auto-register this service with EventDiscoveryService
// Use setImmediate to ensure all dependencies are resolved
setImmediate(async () => {
try {
const eventDiscoveryService = this.eventDiscoveryService;
if (eventDiscoveryService && typeof eventDiscoveryService.addServiceForAutoRegistration === 'function') {
await eventDiscoveryService.addServiceForAutoRegistration(this);
}
}
catch (error) {
console.debug(`Auto-registration failed for ${target.name}:`, error.message);
}
});
};
};
}