注:この記事は、nestjsを初めて学習した後のブロガーの知識と理解のみを記録しています。経験はまだ浅く、記事の内容は参照用です。エラーがあれば訂正してください。
側面として
この記事では一時的に詳細については説明しません
1.アスペクトタイプ:NestInterceptorインターフェイス実装クラス
2.アスペクト入力
ExecutionContextオブジェクト:パラメータホストオブジェクトに継承された実行コンテキストオブジェクトArgumentsHost
次の機能
3.アスペクト出力:次に次のアスペクトを入力します(インターセプター後のロジックを実行できます)
4.使用シナリオの側面
- 関数実行の前後に追加のロジックをバインドする
- 関数から返された結果を変換します
- 関数からスローされた例外を変換する
- 拡張された基本機能の動作
- 選択した条件(キャッシング目的など)に応じて関数を完全に書き直します
インターセプターの単純なケース
1.インターセプターの定義
import {
Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import {
Observable } from 'rxjs';
import {
tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// return之前:前拦截器逻辑
console.log('Before...');
const now = Date.now();
return next
.handle()// handle之后:后拦截器逻辑
.pipe(
// catchError(err => throwError(new BadGatewayException())),// 覆盖异常,在异常过滤器切面之前
tap(() => console.log(`After... ${
Date.now() - now}ms`)),
);
}
}
2.インターセプターバインディング
- メソッドにバインド
@UseInterceptors(LoggingInterceptor)
export class CatsController {
}
- グローバルにバインド(app.module.ts)
import {
Module } from '@nestjs/common';
import {
APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
],
})
export class AppModule {
}