43 lines
944 B
TypeScript
43 lines
944 B
TypeScript
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,
|
|
})),
|
|
);
|
|
}
|
|
}
|