Nest.js 拦截器

时间:2024-01-20 08:18:21

Docs: https://docs.nestjs.com/interceptors

该对象包含从路由处理程序返回的值

在方法执行之前/之后绑定额外的逻辑

转换函数返回的结果

转换从函数抛出的异常

// logging.interceptor.ts

import { ExecutionContext, Injectable, NestInterceptor, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError, of } from 'rxjs';
import { tap, map, catchError } from 'rxjs/operators'; @Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
const now = Date.now(); if(true){ // 硬编码,直接返回 []
return of([])
}
return call$.pipe( catchError(err => {
return throwError(new HttpException('拦截错误', HttpStatus.BAD_GATEWAY))
}), tap(() => {
console.log(`${Date.now() - now}ms`);
}), map((data) => { // data 为路由的返回值
console.log(data)
return data
})
);
}
}

5到6变化

// Before
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
call$: Observable<T>,
): Observable<Response<T>> {
return call$.pipe(map(data => ({ data })));
}
} // After
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
return next
.handle()
.pipe(map(data => ({ data })));
}
}