Reut Schremer
Reut Schremer

Reputation: 368

Service inheritance in Nestjs and controllers

I'm trying to write some generic code for user module, that will be easy to extend. I'm having trouble with dependencies. I have UserService, User entity, ExtendedUserService and ExtendedUserModule and ExtendedUserController.

I want to define that the ExtendedUserController will receive a service that extends typeof UserService (because I want this controller to be used in modules, and on save I want to save more info using any relevant service ).

export class EmailUserController {
    constructor(
        private readonly emailService: UserService
    ) {

If I do so, I have problem of dependencies when I send ExtendedUserService,even though it extends UserService.

Nest can't resolve dependencies of the EmailUserController (?). Please make sure that the argument UserService at index [0] is available in the EmailUserModule context.

The module looks that way:

@Module({
    imports: [
        RoleModule,
        TypeOrmModule.forFeature([EmailUser]),
        JwtModule.register({
            secret: jwtConstants.secret,
            signOptions: { expiresIn: '100min' },
        })
    ],
    providers: [
        EmailUserService, // Extends UserService
        {
            provide: 'CONFIG_OPTIONS',
            useValue: options,
        },
    ],
    exports: [EmailUserService],
    controllers: [EmailUserController]
})

Any idea? Thanks!

Upvotes: 2

Views: 9425

Answers (2)

Porcellus
Porcellus

Reputation: 579

What NestJS does is tries to resolve dependencies, is to get something that provides the exact class - not something that satisfies the same interface, which would be the case if it took extends into account. It would be especially confusing since this could be true for multiple classes.

The standard solution to this is to use a custom class provider (see here).

You could update the module like this:

  providers: [
    EmailUserService,
    {
      provide: UserService,
      useClass: EmailUserService, // Extends UserService
    },
    {
      provide: 'CONFIG_OPTIONS',
      useValue: options,
    },
  ],

Upvotes: 2

kadim kareem
kadim kareem

Reputation: 145

be sure you imported UserModule inside EmailUserModule and be sure you put UserService in providers section in UserModule

Upvotes: 0

Related Questions