From 8395e69e7c72957fa6341bacd500f0c5c3774c26 Mon Sep 17 00:00:00 2001 From: zhenyuWang <13641039885@163.com> Date: Sat, 18 Nov 2023 16:49:31 +0800 Subject: [PATCH] feat: interceptor --- .../wrap-response.interceptor.spec.ts | 7 +++++++ .../wrap-response.interceptor.ts | 20 +++++++++++++++++++ src/main.ts | 2 ++ 3 files changed, 29 insertions(+) create mode 100644 src/common/interceptors/wrap-response/wrap-response.interceptor.spec.ts create mode 100644 src/common/interceptors/wrap-response/wrap-response.interceptor.ts diff --git a/src/common/interceptors/wrap-response/wrap-response.interceptor.spec.ts b/src/common/interceptors/wrap-response/wrap-response.interceptor.spec.ts new file mode 100644 index 0000000..116d770 --- /dev/null +++ b/src/common/interceptors/wrap-response/wrap-response.interceptor.spec.ts @@ -0,0 +1,7 @@ +import { WrapResponseInterceptor } from './wrap-response.interceptor'; + +describe('WrapResponseInterceptor', () => { + it('should be defined', () => { + expect(new WrapResponseInterceptor()).toBeDefined(); + }); +}); diff --git a/src/common/interceptors/wrap-response/wrap-response.interceptor.ts b/src/common/interceptors/wrap-response/wrap-response.interceptor.ts new file mode 100644 index 0000000..eb6b77d --- /dev/null +++ b/src/common/interceptors/wrap-response/wrap-response.interceptor.ts @@ -0,0 +1,20 @@ +// nest g interceptor common/interceptors/wrap-response + +import { + CallHandler, + ExecutionContext, + Injectable, + NestInterceptor, +} from '@nestjs/common'; +// import { Observable, tap } from 'rxjs'; +import { Observable, map } from 'rxjs'; + +@Injectable() +export class WrapResponseInterceptor implements NestInterceptor { + intercept(context: ExecutionContext, next: CallHandler): Observable { + console.log('Before...'); + // return next.handle().pipe(tap((data) => console.log('After...', data))); + // 将返回的数据放到 {data: xxx} 中 + return next.handle().pipe(map((data) => ({ data }))); + } +} diff --git a/src/main.ts b/src/main.ts index c0fc435..0d0ef33 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,6 +2,7 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; import { HttpExceptionFilter } from './common/filters/http-exception/http-exception.filter'; +import { WrapResponseInterceptor } from './common/interceptors/wrap-response/wrap-response.interceptor'; async function bootstrap() { const app = await NestFactory.create(AppModule); @@ -18,6 +19,7 @@ async function bootstrap() { }), ); // 全局管道 app.useGlobalFilters(new HttpExceptionFilter()); // 全局过滤器 + app.useGlobalInterceptors(new WrapResponseInterceptor()); // 全局拦截器 await app.listen(3000); } bootstrap();