如何将Axios响应数据反序列化为NestJS中的类实例?
问题:NestJS中Axios返回的DTO无法调用类方法
在NestJS应用里用Axios调用外部API时,已指定响应类型为ResponseDto,但拿到的response.data是普通JavaScript对象,调用ResponseDto中定义的isValid()方法时会报错:
TypeError: response.data.isValid is not a function
相关代码
ResponseDto 类
import { InfoDto } from './info.dto'; import { Type } from 'class-transformer'; export class ResponseDto { @Type(() => InfoDto) private infos: InfoDto[]; isValid(): boolean { return this.infos.length > 0; } }
InfoDto 类
export class InfoDto { private readonly message: string; isMessageEmpty(): boolean { return !this.message; } }
API调用代码
this.httpService.axiosRef .post<ResponseDto>(apiUrl, request, { headers: headers, }) .then((response) => response.data);
现象
实际返回的是普通对象:
Object { "infos": Array(1)[ Object { "message": "message" } ] }
期望返回的是类实例:
ResponseDto { "infos": Array(1)[ InfoDto { "message": "message" } ] }
解决方案
TypeScript的泛型<ResponseDto>只是类型注解,不会自动把Axios返回的JSON对象转换成类实例。要实现转换,需要用class-transformer库的plainToInstance方法,它会根据类上的装饰器(比如@Type)把普通对象转成对应的类实例。
修改后的API调用代码
import { plainToInstance } from 'class-transformer'; // ... this.httpService.axiosRef .post<ResponseDto>(apiUrl, request, { headers: headers, }) .then((response) => { // 把普通对象转成ResponseDto实例 const responseDto = plainToInstance(ResponseDto, response.data); // 现在可以正常调用isValid方法 console.log(responseDto.isValid()); return responseDto; });
注意事项
- 确保已安装
class-transformer:
npm install class-transformer # 或使用yarn yarn add class-transformer
- 类中的私有属性(比如
infos、message)建议改为受保护(protected)或公共(public),或添加getter方法。因为plainToInstance默认无法直接设置私有属性,不符合TypeScript访问控制规范。
修改后的ResponseDto示例:
import { InfoDto } from './info.dto'; import { Type } from 'class-transformer'; export class ResponseDto { @Type(() => InfoDto) protected infos: InfoDto[]; isValid(): boolean { return this.infos.length > 0; } getInfos(): InfoDto[] { return this.infos; } }
内容的提问来源于stack exchange,提问作者KnownUnknown
相关产品推荐
相关产品推荐

