IntersectionType不能与类转换器一起工作 [英] IntersectionType doesn't work with class-transformer

查看:0
本文介绍了IntersectionType不能与类转换器一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个相交的类

export class PagingDto {
  @IsInt()
  @Type(() => Number)
  @ApiProperty()
  limit: number;

  @IsInt()
  @Type(() => Number)
  @ApiProperty()
  offset: number;
}

export class UserDto {
  @IsString()
  @ApiProperty()
  name: string;
}

export class UserWithPagingDto extends IntersectionType(
  PagingDto,
  UserDto,
) {}

当我尝试将其与@Query()一起使用时,nestjs没有按照预期将Limit&;Offset字符串值转换为数字...

// ----- in UserController
@Get()
  find(@Query() dto: UserWithPagingDto) {
    console.log(dto)
    // output: { limit: '10', offset: '1', name: 'foo' }
    // limit & offset should be numbers...
  }


// ----- in main.ts, following config is defined to enable validation with transform
app.useGlobalPipes(
    new ValidationPipe({ transform: true }),
  );

如果我只是将用PagingDto编写的所有内容都放在UserWithPagingDto中,它就可以正常工作。

这是否意味着Nest不支持具有IntersectionType的类转换器,或者是否有解决方法?

推荐答案

类转换器使用最低配置的IntersectionType: app.useGlobalPipes(new ValidationPipe({transform: true}));
这只是一个@nestjs/swagger库的版本问题。 在我的例子中,将nestjs从7提升到8(有效地将@nestjs/swagger从4.5.12-next.1提升到5.1.2)解决了这个问题。

<;偏离主题,但很有用的备注
如果启用transformOptions: { enableImplicitConversion: true }选项,则即使没有@Type(() => Number)修饰符,也会将字符串转换为数字。

(非常感谢@Jay McDoniel)

这篇关于IntersectionType不能与类转换器一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆