Guard的主要用途為驗證與授權,執行在Middleware之後、interceptor之前
NestCLI指令:$nest g guard <GUARD_NAME>
產生後的程式碼:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
return true;
}
}
基本骨架解析:
和Exception filter差不多,根據需求分成兩種:
1.只針對單一Handler:添加的@UseGuards(<GUARD_NAME>)擺放位置在該Handler上
(在app.controller.ts中)
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from './guards/auth/auth.guard';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@UseGuards(AuthGuard)
@Get()
getHello(): string {
return this.appService.getHello();
}
}
2.針對Controller中的所有Handler:@UseGuards(<GUARD_NAME>)擺放位置在Controller上
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from './guards/auth/auth.guard';
@UseGuards(AuthGuard)
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}