Junior — Middle
Can you describe the sequence of processing incoming requests in NestJS?
sobes.tech AI
Answer from AI
In NestJS, the processing of an incoming HTTP request occurs in several stages:
- Request reception — Express (or Fastify) receives the HTTP request.
- Middleware — the request passes through middleware, which can modify the request or perform additional actions (logging, authentication, etc.).
- Guards — check whether access to a specific route is permitted (e.g., authorization).
- Interceptors — can modify request or response data, perform additional operations before and after the handler is called.
- Pipes — transform and validate incoming data (e.g., converting strings to numbers).
- Controller handler — the method of the controller corresponding to the route is invoked.
- Result processing — the handler's result can be further processed by interceptors.
- Response sending — the formed response is sent to the client.
Example of a simplified flow:
@Get(':id')
@UseGuards(AuthGuard)
@UsePipes(ValidationPipe)
getItem(@Param('id') id: number) {
return this.itemsService.findById(id);
}
Here, first, the guard checks access, then the pipe validates the parameter, and finally, the controller method is called.