メインコンテンツまでスキップ

第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}`;
}

➡️ GET /users/5id数値 5 として受け取れる。


3.3 ガード(Guards)

  • 役割:リクエストが実行される前に「許可するか」を判定する。
  • 認証・認可(Authorization)に使うのが一般的。

📌 例:ログイン必須ガード

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest();
return !!req.user; // ユーザー情報があれば許可
}
}

➡️ コントローラーに適用:

@UseGuards(AuthGuard)
@Get('profile')
getProfile() {
return 'This is profile page';
}

3.4 インターセプター(Interceptors)

  • 役割:リクエストやレスポンスの 前後処理 を挟み込む。
  • 主な用途:
    • ロギング
    • レスポンスの変換
    • キャッシュ
    • 例外の共通処理

📌 例:レスポンスをラップするインターセプター

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
return next.handle().pipe(map(data => ({ data, success: true })));
}
}

➡️ レスポンスが { data: ..., success: true } 形式に統一される。


3.5 フィルター(Exception Filters)

  • 役割:例外をキャッチし、統一的なレスポンスを返す。
  • デフォルトでは NestJS が HttpException を処理するが、カスタム可能。

📌 例:カスタム例外フィルター

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = exception.getStatus();

response.status(status).json({
statusCode: status,
message: exception.message,
});
}
}

➡️ コントローラーに適用:

@UseFilters(HttpExceptionFilter)
@Get()
findAll() {
throw new HttpException('Forbidden', 403);
}

3.6 まとめ

  • デコレーター:NestJS の基本的な構文(ルート・依存性注入など)。
  • パイプ:データを変換・検証。
  • ガード:リクエストを実行するかどうかを制御。
  • インターセプター:前後処理でレスポンスやログを操作。
  • フィルター:例外を一元管理し、統一的なレスポンスを返す。