Using multiple controllers within a single module in NestJS?

Viewed 251

I was reading about the Router Module in NestJS docs:

https://docs.nestjs.com/recipes/router-module

and the sentence:

each controller defined inside the Module

got me trying to think of a situation where I may want multiple controllers in a single module, but I can't think of any situations where this is the case.

If I have a set of three very closely related controllers, would it be wise to encapsulate them in the same module?

How similar does a set of controllers have to be to want to keep them in the same module? What are the pros and cons?

2 Answers

Maybe the only use case might be when you have different versions of your API and wants some previous versions to be still used in the newest ones.

I would not recommend doing nested controllers tho. In express routers, create some sort of routers tree where a child knows nothing about its parent, while in Nestjs, as you said, each controller is a route. I do not think it is possible to create nested controllers.

But there is a workaround it tho. You can use policies whereby a controller has its policy, and when the user hits that route, the policies have their custom logic for fetching data and adding it to the request object. This means it stays in the context, and a similar process would be done if you need to fetch something from that route to another one. Think of this as having to fetch data from a user and then using that same router to fetch a product based on that user.

  • If you have large files, it might be handy to split a controller into many files/controller (although you might have other problems if this is the case).

  • If you have many related things in a module, say like 'monsters' you may want to have a 'dragon controller', and an 'ogre controller'.

  • As @Mamane19 says - versioning an API

  • Because you can?

Related