NestJS で Response オブジェクトを直接操作する際、@Res({ passthrough: true })
オプションを使用することで、NestJS の標準的な機能を維持しながら Response を操作できる。
passthrough: false(デフォルト)の場合
@Post('example')
handleExample(@Res() res: Response) {
res.send('Hello');
// NestJS のインターセプター、例外フィルターなどがバイパスされる
// 完全に手動でレスポンスを制御する必要がある
}
passthrough: true の場合
@Post('example')
handleExample(@Res({ passthrough: true }) res: Response) {
// Response で一部操作(ヘッダー設定など)
res.type('text/plain');
// NestJS の機能(インターセプター等)は引き続き動作
return 'Hello'; // または res.send('Hello');
}
実用例: Webhook validation response
Microsoft Graph の Webhook 検証で text/plain レスポンスが必要な場合:
@Post('webhook')
async handleWebhook(
@Query('validationToken') token: string | undefined,
@Res({ passthrough: true }) res: Response,
) {
if (token) {
res.type('text/plain').send(token);
return; // 早期リターンで処理終了
}
// 通常の処理...
}
passthrough を使うことで、特定のレスポンス要件(Content-Type 等)を満たしつつ、NestJS のエコシステムの恩恵を受けられる。