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();