How to inject repository providers into an entity in Nestjs (not TypeORM)

Viewed 17

How could a repository provider be injected in a plain entity class in NestJS?

In the following code, this.customerRepository is not injected by NestJS, is undefined.

export class UserAggregateEntity  {
  
  @Inject()
  public customerRepository: CustomerRepository;

  private customer: CustomerEntity;

  constructor(private user: UserEntity) {}

  async createCustomer(customer: CustomerEntity): Promise<string> {
    customer.user = this.root.id;

    // here error Cannot read property 'create' of undefined
    const savedCustomer = await this.customerRepository.create(customer); 
    this.customer = savedCustomer;

    return customer.id;
  }
}

UserAggregateEntity class is called by something like...

const userAggregate = new UserAggregateEntity(user);
await userAggregate.createCustomer(customer);

CustomerRepository cannot be instantiated in the createCustomer method because it has to be injected with a DAO and other providers.
CustomerRepository is @Injectable(), defined as provider in the module, and used elsewhere successfully.

Thanks

1 Answers

If you are calling new WhateverClass() yourself, then you are in charge of whatever that class may need to function. Nest will do absolutely no injection on classes that you manage creating yourself, nor should it. There's no hooks set up for watching for the creation of the class or modification of the constructor prototype, all of the metadata nd decorators we use are just there so that Nest can read the metadata and know how to create the class when you ask Nest to. Calling new bypasses that entire system. So you'll need to call new UserAggregateEntity() and have some sort of setter for the customerRepository property that you pass the repository to.

Related