パイプ は、ルートハンドラーに到達する前に入力データを 変換または検証 するクラスです。コントローラーメソッドの引数に対して動作します — それらを変換したり(例:string → number)、検証したり(無効なデータを拒否したり)します。NestJSの検証はパイプの上に構築されています。
Built-in transformation pipes
()
() {
..(id);
}
変換パイプは入力を正しい型に変換します(ルートパラメータ/クエリは常に文字列)。変換ができない場合は400で失敗します。
// enable globally in main.ts
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // remove properties not declared in the DTO
forbidNonWhitelisted: true, // throw if unknown properties are present
transform: true, // turn plain objects into DTO instances, convert types
}));
// with a DTO using class-validator decorators:
export class CreateUserDto {
@IsEmail() email: string;
@MinLength(8) password: string;
}
@Post()
create(@Body() dto: CreateUserDto) { // ValidationPipe validates the body automatically
// if invalid → 400 with details, BEFORE this runs
}
ValidationPipe は DTO の class-validator デコレーターを読み込み、受信データを自動的に検証します — 失敗時には詳細な400エラーを返すため、ハンドラーは常に有効なデータのみを受け取ります。
Request → ...middleware/guards/interceptors... → PIPES (transform/validate) → Handler
Pipes run JUST BEFORE the route handler, operating on its method arguments.
@Injectable()
export class TrimPipe implements PipeTransform {
transform(value: any) {
return typeof value === "string" ? value.trim() : value; // custom transformation
}
}
// usage: @Body(TrimPipe) ...
PipeTransform の transform() メソッドを実装して、カスタム検証/変換ロジックを実装します。
@UsePipes(new ValidationPipe()) // method or controller level
@Param("id", ParseIntPipe) // parameter level
app.useGlobalPipes(new ValidationPipe()) // global (most common for validation)
パイプは入力を安全に処理するためのNestJSの重要な機能であり、フレームワークの 検証システム の基盤です。
ほぼすべてのAPIエンドポイントが入力の検証と変換を必要とするため、これらを理解することは不可欠です:変換パイプ(ParseIntPipe など)はパラメータが正しい型であることを保証し、最も重要なのは、ValidationPipe とDTO を組み合わせることで、リクエストボディに対する class-validator ルールの自動的で宣言的な検証が提供され、ビジネスロジックに到達する 前に 無効または悪意のある入力を明確なエラーで拒否します。
これはセキュリティ(信頼できない入力の検証/サニタイズ、予期しないプロパティの削除)と堅牢性(ハンドラーは有効なデータのみを受け取る)の両方にとって重要です。
グローバル検証パイプを適切なオプション(whitelist、transform)で有効にする方法、ビルトイン変換パイプを使用する方法、カスタムパイプを記述する方法を知ることは、安全で十分に構造化されたNestJS APIを構築するために基本的です — パイプと検証はフレームワークの日常的で必須の概念です。