0
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 Pipe

Posted at

Pipeとは

Pipeは、ハンドラーがリクエストを受け取る前にリクエストに対して処理を行います。

  • リクエストに対してバリデーションを行う
  • リクエストに対してデータの変換を行う
  • リクエストに対して認証を行う
  • 例外を返す

NestJSの組み込みPipe

NestJSには、組み込みのPipeが用意されています。

Pipe 説明
ValidationPipe リクエストに対してバリデーションを行う
ParseIntPipe リクエストのパラメータを数値に変換する
ParseFloatPipe リクエストのパラメータを浮動小数点に変換する
ParseBoolPipe リクエストのパラメータを真偽値に変換する
ParseArrayPipe リクエストのパラメータを配列に変換する
ParseUUIDPipe リクエストのパラメータをUUIDに変換する
ParseEnumPipe リクエストのパラメータを列挙型に変換する
DefaultValuePipe リクエストのパラメータのデフォルト値を設定する
ParseFilePipe リクエストのファイルをパースする

Pipeを適用する

Pipeを適用するには、パイプを適用したいハンドラーの引数に@UsePipesデコレータを付与します。

@Get(':id')
@UsePipes(new ParseIntPipe())
findOne(@Param('id') id: number) {
  return this.catsService.findOne(id);
}

Pipeをパラメータに適応する

@Paramの引数にパイプを適用することもできます。

@Get(':id')
findOne(@Param('id', new ParseIntPipe()) id: number) {
  return this.catsService.findOne(id);
}

Pipeをグローバルに適用する

main.tsでアプリケーション全体にPipeを適応することができます。

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();

参考

0
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
0
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?