Last active
February 19, 2023 01:35
-
-
Save LuckyArdhika/2ed1afb5873d1abad3e343bad215d9c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// main.ts | |
app.useGlobalInterceptors(new TransformResponseInterceptor()); | |
// transformResponse.interceptor.ts | |
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; | |
import { Observable } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
@Injectable() | |
export class TransformResponseInterceptor implements NestInterceptor { | |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> { | |
return next.handle().pipe( | |
map((data) => { | |
console.log(data); // maintained | |
if (data?.options?.isPagination) { | |
data.isPagination = undefined; | |
} | |
return { statusCode: 200, responseCode: 1, data, meta }; | |
}), | |
); | |
} | |
} | |
import { | |
ExceptionFilter, | |
Catch, | |
ArgumentsHost, | |
HttpException, | |
HttpStatus, | |
} from '@nestjs/common'; | |
import { Request, Response } from 'express'; | |
@Catch(BadRequestException) | |
export class BadRequestFilter implements ExceptionFilter { | |
catch(exception: HttpException, host: ArgumentsHost) { | |
const ctx = host.switchToHttp(); | |
const response = ctx.getResponse<Response>(); | |
const status = exception.getStatus(); | |
const message = exception.message; | |
response.status(status).json({ | |
data: { | |
statusCode: status, | |
message: message, | |
}, | |
meta: {}, | |
}); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment