Open5

NestJS stuff

32px32px
  • Guards はミドルウェアより less dumb なやつ
  • ctx.getArgs() で GQL の input がとれる

https://qiita.com/kmatae/items/da60d82dac9164a3855e
https://docs.nestjs.com/guards
https://stackoverflow.com/questions/63585893/graphql-nestjs-how-can-i-access-args-in-a-guard

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,
  }
}
32px32px

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