Dev Study
NestJS コース

14. インターセプター — 処理の前後に割り込む

インターセプターは、ハンドラの実行を前後から挟み込む部品です。NestInterceptor インターフェースの intercept() を実装し、next.handle() を呼ぶとハンドラ本体が実行されます。その呼び出しの前後にコードを置けるため、「実行前の準備」と「実行後の加工」を1か所に書けます。

実務での代表例は、処理時間の計測ログと、レスポンスを { data: ... } のような共通フォーマットに包む整形です。全ハンドラに同じ前後処理を入れたいと感じたら、インターセプターの出番だと考えてよいでしょう。

つまずきポイントは戻り値が RxJS の Observable であることです。深入りは不要で、「next.handle() の後ろに .pipe(tap(...)) や .pipe(map(...)) をつなぐと実行後の処理を書ける」というパターンだけ覚えれば実務の大半はこなせます。

サンプルコード(フレームワーク環境が必要なため表示のみ)

import {
  CallHandler, ExecutionContext, Injectable, NestInterceptor,
} from "@nestjs/common";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<unknown> {
    const started = Date.now(); // ← ハンドラ実行前
    return next.handle().pipe(
      // ← ハンドラ実行後
      tap(() => console.log("処理時間: " + (Date.now() - started) + "ms"))
    );
  }
}
// 適用: @UseInterceptors(LoggingInterceptor)
公式ドキュメントで詳しく ↗