Junior — Middle
What is the main role of controllers in the architecture of a Nest.js application?
sobes.tech AI
Answer from AI
In a Nest.js application architecture, controllers are responsible for handling incoming HTTP requests and returning responses to the client. The main roles of controllers:
- Receive requests from the client (e.g., GET, POST, PUT, DELETE).
- Call the appropriate services or business logic to process data.
- Formulate and send responses back to the client.
Controllers serve as a link between the external interface (API) and the internal components of the application. They are defined using decorators, such as @Controller(), and can have methods with route decorators, such as @Get(), @Post().
Example of a controller in Nest.js:
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get()
findAll() {
return ['user1', 'user2', 'user3'];
}
}
Here, the controller handles GET requests to the /users route and returns a list of users.