Skip to content

Commit

Permalink
feat: interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenyuWang committed Nov 18, 2023
1 parent fa72b55 commit 8395e69
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { WrapResponseInterceptor } from './wrap-response.interceptor';

describe('WrapResponseInterceptor', () => {
it('should be defined', () => {
expect(new WrapResponseInterceptor()).toBeDefined();
});
});
20 changes: 20 additions & 0 deletions src/common/interceptors/wrap-response/wrap-response.interceptor.ts
Original file line number Diff line number Diff line change
@@ -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<any> {
console.log('Before...');
// return next.handle().pipe(tap((data) => console.log('After...', data)));
// 将返回的数据放到 {data: xxx} 中
return next.handle().pipe(map((data) => ({ data })));
}
}
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -18,6 +19,7 @@ async function bootstrap() {
}),
); // 全局管道
app.useGlobalFilters(new HttpExceptionFilter()); // 全局过滤器
app.useGlobalInterceptors(new WrapResponseInterceptor()); // 全局拦截器
await app.listen(3000);
}
bootstrap();

0 comments on commit 8395e69

Please # to comment.