File size: 865 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { map, type Observable } from 'rxjs';
import { Paginated } from '../dto/paginated.dto.js';
import type { ApiSuccess } from '../interfaces/api-response.interface.js';

/** Every successful response becomes `{ success: true, data, meta? }`; empty (204) responses stay empty. */
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ApiSuccess<unknown> | undefined> {
  intercept(_: ExecutionContext, next: CallHandler<T>): Observable<ApiSuccess<unknown> | undefined> {
    return next.handle().pipe(
      map((body) => {
        if (body === undefined) return undefined;
        if (body instanceof Paginated) return { success: true, data: body.items, meta: body.meta };
        return { success: true, data: body };
      }),
    );
  }
}