Open5
NestJS stuff

- Guards はミドルウェアより less dumb なやつ
-
ctx.getArgs()
で GQL の input がとれる
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { GqlExecutionContext } from '@nestjs/graphql'
import { Observable } from 'rxjs'
@Injectable()
export class GoalPersonnelGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const ctx = GqlExecutionContext.create(context)
console.log('----------')
console.log(ctx.getArgs())
return true
}
}
----------
{
input: [Object: null prototype] {
title: 'new post'
createdAt: 2023-10-01T15:45:00.000Z,
}
}

getArgs()
のリンク

Guard でエラーメッセージをカスタマイズしたいときはシンプルに HttpException
を投げればいいらしい
btw UnauthorizedException
is a child class of HttpException
import { UnauthorizedException } from '@nestjs/common'

CurrentUser のしくみ

guard の中で currentUser をとってきたい
All Nest enhancers have a defined order they run in as documented in the request-lifecycle page.
Guard execution starts with global guards, then proceeds to controller guards, and finally to route guards. As with middleware, guards run in the order in which they are bound. For example:
@UseGuards(Guard1, Guard2)
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@UseGuards(Guard3)
@Get()
getCats(): Cats[] {
return this.catsService.getCats();
}
}
このコードの順番は Guard 1 → 2 → 3