Complete the code to apply a guard at the controller level.
import { Controller, UseGuards } from '@nestjs/common'; import { AuthGuard } from './auth.guard'; @UseGuards([1]) @Controller('users') export class UsersController { // controller methods }
UseGuards decorator expects the guard class name without parentheses when applied at the controller level.
Complete the code to apply a guard at the route handler level.
import { Controller, Get, UseGuards } from '@nestjs/common'; import { RolesGuard } from './roles.guard'; @Controller('products') export class ProductsController { @Get() @UseGuards([1]) findAll() { return []; } }
At the route handler level, @UseGuards expects the guard class name without parentheses.
Fix the error in applying a guard globally in main.ts.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LoggingGuard } from './logging.guard'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalGuards([1]); await app.listen(3000); } bootstrap();
When applying a global guard, you must pass an instance of the guard, so use new LoggingGuard().
Fill both blanks to apply multiple guards at the controller level.
import { Controller, UseGuards } from '@nestjs/common'; import { AuthGuard } from './auth.guard'; import { RolesGuard } from './roles.guard'; @UseGuards([1], [2]) @Controller('orders') export class OrdersController { // methods }
You can pass multiple guard classes separated by commas inside @UseGuards.
Fill all three blanks to apply a guard globally and override it at controller and route levels.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { GlobalGuard } from './global.guard'; import { ControllerGuard } from './controller.guard'; import { RouteGuard } from './route.guard'; import { Controller, UseGuards, Get } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalGuards([1]); await app.listen(3000); } @UseGuards([2]) @Controller('items') class ItemsController { @Get() @UseGuards([3]) findAll() { return []; } } bootstrap();
Global guards require instances, so use new GlobalGuard(). Controller and route guards use class names without parentheses.