第03章 コア概念
NestJS は デコレーター をベースに、さまざまな共通処理を直感的に実装できます。代表的な仕組みは以下の5つです。
- デコレーター(Decorators)
- パイプ(Pipes)
- ガード(Guards)
- インターセプター(Interceptors)
- フィルター(Exception Filters)
3.1 デコレーター(Decorators)
- 役割:クラスやメソッドに「メタ情報」を付与する仕組み。
- NestJS のルーティングや DI の中心的存在。
📌 例:
@Controller('users')
export class UsersController {
@Get(':id')
findOne(@Param('id') id: string) {
return `User #${id}`;
}
}
@Controller('users')→/usersルートを定義@Get(':id')→/users/:idに対応@Param('id')→ URL パラメータを取得
3.2 パイプ(Pipes)
- 役割:データの 変換 と バリデーション。
- リクエストデータを処理して、コントローラーに渡す前に整形できる。
📌 組み込み例:
ValidationPipe→ DTO を使って入力データを検証ParseIntPipe→ 文字列を数値に変換
📌 サンプル:
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return `User #${id}`;
}