1st commit
This commit is contained in:
42
src/common/interceptors/response.interceptor.ts
Normal file
42
src/common/interceptors/response.interceptor.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { map, Observable } from 'rxjs';
|
||||
|
||||
export interface StandardApiResponse<T> {
|
||||
success: boolean;
|
||||
statusCode: number;
|
||||
path: string;
|
||||
timestamp: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ResponseInterceptor<T>
|
||||
implements NestInterceptor<T, StandardApiResponse<T>>
|
||||
{
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Observable<StandardApiResponse<T>> {
|
||||
const http = context.switchToHttp();
|
||||
const response = http.getResponse();
|
||||
const request = http.getRequest();
|
||||
|
||||
return next.handle().pipe(
|
||||
map((data) => ({
|
||||
success: true,
|
||||
statusCode: response.statusCode,
|
||||
path: request.url,
|
||||
timestamp: new Date().toISOString(),
|
||||
data,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user