统一请求成功的返回数据
1、创建拦截器
npx nest g in interceptor/transform
2、拦截器代码
import {
Injectable,
NestInterceptor,
CallHandler,
ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
data: T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext,next: CallHandler<T>,): Observable<Response<T>> {
return next.handle().pipe(map(data => {
return {
data,
code: 0,
message: '请求成功',
};
}),
);
}
}
3、在main.ts中全局注册
import { Logger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {TransformInterceptor} from './transform.interceptor'
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe())
app.useGlobalInterceptors(new TransformInterceptor())
await app.listen(3000,() => {
Logger.log('服务已经启动,请访问localhost:3000')
});
}
bootstrap();
网友评论