I came up with an EventService to manage custom events that are added through a special decorator. Everything appears to be functioning correctly, but the issue arises when attempting to access the methods within the stored event class as they return undefined.
The puzzling part is that the class itself seems to be initialized.
What could be causing this particular behavior?
event.service.ts
@Injectable()
/**
* @class EventService
*/
export class EventService {
/**
* @private
* @readonly
* @type {Logger}
*/
private readonly logger: Logger = new Logger(EventService.name);
/**
* Event Storage
*
* @private
* @readonly
* @type {Map<string, BaseEvent>}
*/
private readonly _events: Map<string, BaseEvent> = new Map<
string,
BaseEvent
>();
/**
* Add Event
*
* @public
* @async
* @param {string} key Event Name
* @param {BaseEvent} event Event Class
* @param {boolean} overwrite Overwrite Event in Map
* @returns {Promise<void>}
*/
public async add(
key: string,
event: BaseEvent,
overwrite = false
): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const className = (event as any).name;
const hasRegistered = await this.has(key);
if (hasRegistered && !overwrite) {
this.logger.error(`${key} already registered with: ${className}`);
return;
}
if (hasRegistered && overwrite) {
this._events.set(key, event);
this.logger.log(
`${key} got overwritten by event class: ${className}`
);
return;
}
this._events.set(key, event);
console.log(event);
console.log(event.test);
this.logger.log(`${key} was registered to: ${className}`);
}
}
event.decorator.ts
/**
* Bind Event to Class
*
* @function
* @param {string} name Event Name
* @param {boolean} client Determinate if its a client event
* @param {string} overwrite Overwrite existing event
*/
export function Event(name: string, client = false, overwrite = false): any {
return (constructor: any) => {
return class extends constructor {
constructor(...args: any[]) {
super(args);
const eventService: EventService = this.eventService[0];
eventService.add(name, constructor, overwrite);
}
};
};
}
player-join.event.ts
@Injectable()
@Event('playerJoin')
export class PlayerJoinEvent extends BaseEvent {
/**
* @private
* @readonly
* @type {Logger}
*/
public readonly logger: Logger = new Logger(PlayerJoinEvent.name);
/**
* Handle Player Join
*
* @public
* @async
* @param {any} player Joining Player
* @returns {Promise<void>}
*/
public async execute(player: string): Promise<void> {
this.logger.log(`${player} joined the server`);
}
public test(): void {
this.logger.debug('hi');
}
}
Console Output
[Nest] 22508 - 20.09.2022, 19:44:48 LOG [NestFactory] Starting Nest application...
[Nest] 22508 - 20.09.2022, 19:44:48 LOG [InstanceLoader] AppModule dependencies initialized +24ms
[class PlayerJoinEvent extends BaseEvent] // these both logs are in the EventService.ts after adding them
undefined
[Nest] 22508 - 20.09.2022, 19:44:48 LOG [EventService] playerJoin was registered to: PlayerJoinEvent