NestJS Basic 3 — Questions and Answers
Question 1: What is the role of the @Module() decorator's 'providers' array?
- Lists controllers to register
- Declares services and other providers available for injection within the module (Correct answer)
- Imports other modules
- Exports providers to other modules
Correct answer: Declares services and other providers available for injection within the module
The 'providers' array in @Module() registers injectable services that the NestJS IoC container manages.
Question 2: Which decorator allows you to read the entire request body in a NestJS controller method?
- @Req()
- @Param()
- @Body() (Correct answer)
- @Query()
Correct answer: @Body()
@Body() extracts the full request payload (body) and passes it to the method parameter.
Question 3: What does the 'imports' array in @Module() do?
- Imports TypeScript files
- Makes exported providers from other modules available in the current module (Correct answer)
- Declares new providers
- Registers middleware
Correct answer: Makes exported providers from other modules available in the current module
The 'imports' array brings in other modules, making their exported providers available for injection.
Question 4: In NestJS, pipes are typically used to:
- Log HTTP requests
- Transform and validate incoming request data (Correct answer)
- Handle database connections
- Serve static files
Correct answer: Transform and validate incoming request data
Pipes in NestJS process incoming data — they can transform it (e.g., string to int) or validate it before it reaches the handler.
Question 5: What is the default HTTP server used by NestJS under the hood?
- Fastify
- Koa
- Express (Correct answer)
- Hapi
Correct answer: Express
NestJS uses Express as its default underlying HTTP server, though Fastify is also supported.
Question 6: Which built-in pipe would you use to parse and validate a route param as an integer?
- ValidationPipe
- ParseIntPipe (Correct answer)
- IntegerPipe
- TransformPipe
Correct answer: ParseIntPipe
ParseIntPipe converts a string route parameter to a JavaScript integer and throws a 400 if conversion fails.
Question 7: How do you apply a pipe globally to all routes in NestJS?
- Add it to the module providers array
- Use app.useGlobalPipes() in main.ts (Correct answer)
- Apply @UsePipes() to every controller
- Register it in app.module.ts imports
Correct answer: Use app.useGlobalPipes() in main.ts
Calling app.useGlobalPipes() in main.ts registers a pipe that runs for every incoming request across all routes.
What is the role of the @Module() decorator's 'providers' array?