Search code examples
mongoosenestjsnestjs-mongoose

How to inject dependency in abstract class with NestJs?


Let's say I have an abstract service like bellow

abstract class AbstractService {
  @InjectConnection() connection: Connection
}

and UserService will extends AbstractService

class UserService extends AbstractService {
  async get () {
    this.connection //undefined
  }
}

I cannot access the connection when I extend AbstractService but it works with a single class

class UserService {
  @InjectConnection() connection: Connection
  async get () {
    this.connection //mongoose connection
  }
}

and I call UserService#get in the controller

@Controller(ROUTER.USER)
export class UserController{
  constructor(private readonly service: UserService) { }
  @Get()
  get() {
    return this.service.get
  }
}

Solution

  • when UserService extends AbstractService it will extend all its members such as methods or constructor but it will not do for connection because it is a decorator that has to be injected that is why this.connection is undefined in the first example, so you have to deal with that.
    in the second example, UserService does not extend anything and has its own connection so it works that's obvious, but we need to extend AbstractService so we can use its methods.
    one solution is to make UserService has its own connection, and once created call the parent class constructor passing connection to it.
    in this case, the get() method will return the expected connection:

    abstract class AbstractService {
      constructor(@InjectConnection() connection: Connection) {}
    }
    
    class UserService extends AbstractService {
      constructor(@InjectConnection() connection: Connection) {
        super(connection);
      }
    async get() {
        this.connection
      }
    }