Skip to content

Instantly share code, notes, and snippets.

@LuckyArdhika
Last active February 19, 2023 01:35
Show Gist options
  • Save LuckyArdhika/2ed1afb5873d1abad3e343bad215d9c9 to your computer and use it in GitHub Desktop.
Save LuckyArdhika/2ed1afb5873d1abad3e343bad215d9c9 to your computer and use it in GitHub Desktop.
// 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