NestJS Basic 4 — Questions and Answers
Question 1: What is the purpose of Guards in NestJS?
- To transform response data
- To determine whether a request should be handled by the route handler (authorization) (Correct answer)
- To catch and handle exceptions
- To validate request body schemas
Correct answer: To determine whether a request should be handled by the route handler (authorization)
Guards implement CanActivate and decide whether a request proceeds to the handler, making them ideal for authentication and authorization.
Question 2: Which interface must a NestJS Guard implement?
- NestMiddleware
- CanActivate (Correct answer)
- ExceptionFilter
- PipeTransform
Correct answer: CanActivate
A guard must implement the CanActivate interface, which requires a canActivate() method returning boolean or Observable<boolean>.
Question 3: What is an Interceptor in NestJS primarily used for?
- Routing requests to different controllers
- Binding extra logic before/after method execution and transforming results (Correct answer)
- Validating request parameters
- Managing database transactions
Correct answer: Binding extra logic before/after method execution and transforming results
Interceptors wrap route handler execution, allowing you to add logging, transform responses, or handle errors around the handler call.
Question 4: In NestJS, which decorator is used to handle exceptions thrown within a controller?
- @UseInterceptors()
- @UseGuards()
- @UseFilters() (Correct answer)
- @UsePipes()
Correct answer: @UseFilters()
@UseFilters() applies an exception filter to a controller or handler to catch and transform thrown exceptions.
Question 5: What does the @Query() decorator extract from a request?
- Named URL path segments
- HTTP request headers
- Query string parameters (?key=value) (Correct answer)
- The request body
Correct answer: Query string parameters (?key=value)
@Query() extracts query string parameters from the URL (e.g., /search?term=nestjs gives @Query('term') = 'nestjs').
Question 6: Which NestJS concept represents a self-contained block of functionality that groups related controllers and providers?
- Service
- Guard
- Module (Correct answer)
- Middleware
Correct answer: Module
A Module organizes related code (controllers, services, etc.) and defines the boundary of a feature area in NestJS.
Question 7: How do you share a provider from one module so other modules can use it?
- Add it to the imports array
- Add it to the exports array of the providing module (Correct answer)
- Declare it as global in main.ts
- Use @Shared() decorator on the provider
Correct answer: Add it to the exports array of the providing module
A module must list a provider in its exports array for other modules that import it to access that provider.
What is the purpose of Guards in NestJS?