samchon / nestia

NestJS Helper Libraries + TypeScript OpenAPI generator
https://nestia.io/
MIT License
1.71k stars 89 forks source link

Nestjs fastify use NestInterceptor auto stringify #868

Closed zaohuayudie closed 3 months ago

zaohuayudie commented 3 months ago

Bug Report

Nestjs+Fastify, the return value is a string, and the expectation is json

controller.ts
@TypedRoute.Get('config')
async test() {
    return { name: 'zaohua', img: ''}
}

When I use TransformInterceptor:

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { FastifyReply } from 'fastify';

interface Response<T> {
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const res = context.switchToHttp().getResponse<FastifyReply<any>>();
    res.header('Content-Type', 'application/json; charset=utf-8');
    return next.handle().pipe(
      map((data) => {
        return {
          data,
          code: 0,
          msg: '请求成功',
        };
      }),
    );
  }
}

GET or Post response data is string
{
  "data": "{\"name\":\"zaohua\",\"img\":\"\"}",
  "code": 0,
  "msg": "请求成功"
}

Summary

Write a short summary of the bug in here.

the same question : https://stackoverflow.com/questions/76884219/disable-nestinterceptor-auto-stringify

samchon commented 3 months ago

@TypedRoute() ensures type safety and boosts up serialization through typia.json.assertStringify() funtion.

Therefore, it is not possible to change the response object through the global interceptor, and it is intended spec of the @TypedRoute(): the responded object type must be same with its DTO type. If you don't want that, you have to use original @Post() or @Get() function of nestjs.

zaohuayudie commented 2 months ago

@TypedRoute() ensures type safety and boosts up serialization through typia.json.assertStringify() funtion.

Therefore, it is not possible to change the response object through the global interceptor, and it is intended spec of the @TypedRoute(): the responded object type must be same with its DTO type. If you don't want that, you have to use original @Post() or @Get() function of nestjs.

Thanks!