1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[NestJS]レスポンスの返却値に特定プロパティを除外する方法

Last updated at Posted at 2023-03-12

はじめに

セキュリティ上、どうしてもDB上から取得したデータに特定プロパティが含まれないようにしたいときがあるかと思います。
そのときの対応方法をまとめています。

方法

Entityクラスに@Exclude({ toPlainOnly: true })を該当プロパティ上に記載する

import { Exclude } from '@nestjs/class-transformer';

export class User {
  id: number;

  email: string;

  @Exclude({ toPlainOnly: true })
  password: string;
}

適用したいcontrollerに

@UseInterceptors(ClassSerializerInterceptor)

もしくはグローバル上で適用したい場合は

app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

こうすることでUserデータを取得したときにパスワードが含まれないようになります。

おまけ

GraphQL(コードファースト)上でも返却値に特定プロパティをを除外する方法があったので記載しておきます。
その方法は該当プロパティ上に@HideField()を付与する。

@ObjectType()
export class User {
    @Filed(() => Int)
    id: number

    @Field()
    email: string

    @HideField()
    password: string
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?