0

I'm following the NestJS docs for creating an EventEmitter (Doc Link. When I running my code I'm getting an error :

"[Nest] 129586 - 16/06/2021, 20:43:31 [ExceptionsHandler] this.eventEmitter.emit is not a function"

This is what my code looks like:

import { EventEmitter2 } from "@nestjs/event-emitter";

@EntityRepository(Auth)
export class AuthRepository extends Repository{


    constructor(private eventEmitter: EventEmitter2) {
        super();
    }

    private logger = new Logger(AuthRepository.name);

    async createUser(authDao: SignUpDto): Promise {

        const { password, username, role, email, dateOfBirth, fname, lname } = authDao;

        let user = await this.findOne({ username });

        if (user) {
            throw new ForbiddenException("Username already taken");
        }

        user = this.create({ password, username, role });

        await this.save(user).catch(e => this.logger.error(e));

        this.eventEmitter.emit("user.created", {
            fname, lname, dateOfBirth, email
        });


    };


} 

I'm not sure what I'm missing here.

Rohit
  • 35
  • 1
  • 7

2 Answers2

3

Nest will not do any DI on TypeORM Repository classes. This is because these classes have other dependencies necessary to them by TypeORM, such as entity managers, and connections. Injecting the EventEmitter is something that should be done in a regular NestJS Provider, and not a TypeO Repo class

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
2

One thing I would mention is that you want the line where you declare your class to look like this:

export class AuthRepository extends Repository<Auth> {

as shown here: https://docs.nestjs.com/techniques/database#custom-repository

The reason that the event emitter is not being injected properly is because Nest is already injecting other things into the constructor of a Repository subclass, so the signature doesn't match.

More importantly, this would be potentially considered a bad design, because the Repository should only be concerned with persistence operations on the entities. You might want to refactor this, and create a Service (Provider), and then inject both the eventEmitter and your repository into it. Then, in that service, you can call the createUser method on the repository instance, and follow it up with emitting the event.

djheru
  • 3,525
  • 2
  • 20
  • 20