#Understanding what must be exported

12 messages · Page 1 of 1 (latest)

opaque cobalt
#

Hiya,

I have a module with the following structure

@Module({
  providers: [APIController, MyService],
  exports: [APIController],
})
export class APIModule {}

which is then imported in my AppModule

@Module({
  imports: [APIModule],
  controllers: [APIController],
})

The controller itself looks something like the following

@Controller('api')
export class APIController {
    constructor(private readonly myService: MyService) {}
}

I would expect this to work fine, as I don't want MyService to be available to other modules in my application, but I do want it to be provided to APIController. However, unless I also add MyService to my exports, I end up with a dependency resolution failure.

[Nest] 846460  - 09/01/2023, 3:22:28 PM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the APIController (?). Please make sure that the argument MyService at index [0] is available in the AppModule context.

Potential solutions:
- Is AppModule a valid NestJS module?
- If MyService is a provider, is it part of the current AppModule?
- If MyService is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing MyService */ ]
  })

Am I missing something? From my reading of the docs, I'd expect this to work, as I am providing the service to my providers, which should thus be made available to the controller.

https://docs.nestjs.com/modules

providers: the providers that will be instantiated by the Nest injector and that may be shared at least across this module

river yacht
#

Controllers don't belong to providers array. And you probably don't want controllers from other modules in your AppService

#

so I guess in your case nothing needs to be exported

opaque cobalt
#

oh really? So is a provider simply "any class that is not a controller"?

river yacht
#
@Module({
  controllers: [APIController]
  providers: [MyService],
})
export class APIModule {}



@Module({
  imports: [APIModule],
})
export class AppModule
opaque cobalt
#

I see. And that will be added to the routing tree automatically?

river yacht
#

if you want a "tree" of controllers, you would need Nest's RouterModule but I wouldn't worry about that just yet

opaque cobalt
#

Gotcha! Thank you. Is there ever a reason to export a controller or make it a provider? If so I might open an issue to generate a warning about this, as it seems like an easy pitfall to fall into

#

(when I said tree, I meant the literal URI tree, but that's semantics, hehe)

river yacht
#

Is there ever a reason to export a controller or make it a provider
No, not really. I don't even think something like that is supported