200번대의 응답시 success: true, 아닐시 success: false
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class SuccessInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => {
const response = context.switchToHttp().getResponse();
const statusCode = response.statusCode;
if (statusCode >= 200 && statusCode < 300) {
return {
success: true,
data,
};
} else {
return {
success: false,
data,
};
}
}),
);
}
}
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { SuccessInterceptor } from './success.interceptor';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: SuccessInterceptor,
},
],
})
export class AppModule {}
위와 같이 설정했을때 자연스럽게 성공 혹은 실패시 그에 맞는 success값이 추가된다.
ex
{
success: true,
data: [
...
]
}