diff --git a/apps/shared/src/interceptors/__tests__/response-format.interceptor.spec.ts b/apps/shared/src/interceptors/__tests__/response-format.interceptor.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..4584333346b681815cc4d42a36eb71dabff5688e --- /dev/null +++ b/apps/shared/src/interceptors/__tests__/response-format.interceptor.spec.ts @@ -0,0 +1,49 @@ +import type { ExecutionContext } from '@nestjs/common'; +import type { TestingModule } from '@nestjs/testing'; + +import { Test } from '@nestjs/testing'; +import { of } from 'rxjs'; + +import { ResponseFormatInterceptor } from '../response-format.interceptor.js'; + +describe('ResponseFormatInterceptor', () => { + let interceptor: ResponseFormatInterceptor; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ResponseFormatInterceptor], + }).compile(); + + interceptor = module.get<ResponseFormatInterceptor>( + ResponseFormatInterceptor, + ); + }); + + it('should be defined', () => { + expect(interceptor).toBeDefined(); + expect(interceptor).toBeInstanceOf(ResponseFormatInterceptor); + }); + + it('should intercept the request and format the response', (done) => { + const context: ExecutionContext = { + switchToHttp: () => ({ + getResponse: () => ({ + statusCode: 200, + }), + }), + } as ExecutionContext; + const next = { + handle: jest.fn().mockReturnValue(of('Hello World')), + }; + + const result = interceptor.intercept(context, next); + + expect(result).toBeDefined(); + expect(next.handle).toHaveBeenCalled(); + + result.subscribe((response) => { + expect(response).toEqual({ statusCode: 200, data: 'Hello World' }); + done(); + }); + }); +}); diff --git a/apps/shared/src/interceptors/response-format.interceptor.ts b/apps/shared/src/interceptors/response-format.interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d85a0ef39bf053fa894984ed985c20ceb9387e3 --- /dev/null +++ b/apps/shared/src/interceptors/response-format.interceptor.ts @@ -0,0 +1,28 @@ +import type { + CallHandler, + ExecutionContext, + NestInterceptor, +} from '@nestjs/common'; + +import { Injectable } from '@nestjs/common'; +import { map, type Observable } from 'rxjs'; + +@Injectable() +export class ResponseFormatInterceptor implements NestInterceptor { + public intercept( + context: ExecutionContext, + next: CallHandler, + ): Observable<unknown> { + const ctx = context.switchToHttp(); + const response = ctx.getResponse(); + + return next.handle().pipe( + map((data) => { + return { + statusCode: response.statusCode, + data, + }; + }), + ); + } +}