| 1 | import { |
| 2 | Injectable, |
| 3 | NestInterceptor, |
| 4 | ExecutionContext, |
| 5 | CallHandler, |
| 6 | } from '@nestjs/common'; |
| 7 | import { Observable } from 'rxjs'; |
| 8 | import { map } from 'rxjs/operators'; |
| 9 | import { Request } from 'express'; |
| 10 | |
| 11 | export interface ApiResponse<T> { |
| 12 | success: boolean; |
| 13 | data: T; |
| 14 | meta: { |
| 15 | timestamp: string; |
| 16 | path: string; |
| 17 | method: string; |
| 18 | }; |
| 19 | } |
| 20 | |
| 21 | @Injectable() |
| 22 | export class TransformInterceptor<T> implements NestInterceptor< |
| 23 | T, |
| 24 | ApiResponse<T> |
| 25 | > { |
| 26 | intercept( |
| 27 | context: ExecutionContext, |
| 28 | next: CallHandler, |
| 29 | ): Observable<ApiResponse<T>> { |
| 30 | const request: Request = context.switchToHttp().getRequest(); |
| 31 | const { method, url } = request; |
| 32 | |
| 33 | return next.handle().pipe( |
| 34 | map((data: T) => ({ |
| 35 | success: true, |
| 36 | data, |
| 37 | meta: { |
| 38 | timestamp: new Date().toISOString(), |
| 39 | path: url, |
| 40 | method, |
| 41 | }, |
| 42 | })), |
| 43 | ); |
| 44 | } |
| 45 | } |