transform http response json

This commit is contained in:
Philipinho
2023-08-05 20:44:15 +01:00
parent 40a459271a
commit 021a99e716
2 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,27 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
export interface Response<T> {
data: T;
}
@Injectable()
export class TransformHttpResponseInterceptor<T>
implements NestInterceptor<T, Response<T>>
{
intercept(
context: ExecutionContext,
next: CallHandler<T>,
): Observable<Response<T>> {
return next.handle().pipe(
map((data) => {
const status = context.switchToHttp().getResponse().statusCode;
return { data, success: true, status };
}),
);
}
}

View File

@ -5,6 +5,7 @@ import {
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { ValidationPipe } from '@nestjs/common';
import { TransformHttpResponseInterceptor } from './interceptors/http-response.interceptor';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
@ -22,6 +23,8 @@ async function bootstrap() {
}),
);
app.useGlobalInterceptors(new TransformHttpResponseInterceptor());
await app.listen(3000);
}
bootstrap();