【问题标题】:using validation pipe in nestjs gives me an classTransformer.plainToclass is not a function error在 nestjs 中使用验证管道给了我一个 classTransformer.plainToclass is not a function 错误
【发布时间】:2021-12-31 08:33:49
【问题描述】:

我正在使用nestjs/graphql,并且我为graphql 突变制作了一个dto,其中我使用了@IsString()@IsBoolean() 等类验证器选项。为此我安装了class-validatorclass-transformer。但是当我进行突变时,它给了我一个闻所未闻的错误。我用谷歌搜索了它,但没有任何结果。 错误是这样的:

[Nest] 5872  - 2021. 11. 21. 오후 7:56:09   ERROR [ExceptionsHandler] classTransformer.plainToClass is not a function
TypeError: classTransformer.plainToClass is not a function
    at ValidationPipe.transform (/home/inust33/ubereats-backend/node_modules/@nestjs/common/pipes/validation.pipe.js:51:39)
    at /home/inust33/ubereats-backend/node_modules/@nestjs/core/pipes/pipes-consumer.js:16:33
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

在操场上,它向我展示了这样的: graphql playground error

我的 dto 看起来像这样:

@ArgsType()
export class createRestaurantDto {
  @Field((type) => String)
  @IsString()
  @Length(5, 10)
  name: string;

  @Field((type) => Boolean)
  @IsBoolean()
  isVegan: boolean;

  @Field((type) => String)
  @IsString()
  address: string;

  @Field((type) => String)
  @IsString()
  ownersName: string;

  @Field(() => String)
  @IsString()
  categoryName: string;
}

我使用这个 dto 的突变是这样的:

 @Mutation(() => Boolean)
  async createRestaurant(
    @Args() createRestaurantDto: createRestaurantDto,
  ): Promise<boolean> {
    try {
      await this.restaurantService.createRestaurant(createRestaurantDto);
      return true;
    } catch (e) {
      console.log(e);
      return false;
    }
  }

我在 main.ts 中进行了验证管道设置,如下所示:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}

我能得到的只是不设置useGlobalPipes 选项,这不是我想要做的,突变效果很好。 你能帮我解决这个问题吗?

【问题讨论】:

    标签: graphql nestjs class-validator class-transformer


    【解决方案1】:

    问题解决了。 由于最近更新,class-transformer@0.5.0在nestJS的validationPipe中使用会报错。

    你应该降级到 class-transformer@0.4.0

    https://github.com/nestjs/nest/issues/8637

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-07
      • 2018-03-19
      • 2021-05-31
      • 2022-08-03
      • 2020-04-24
      • 1970-01-01
      • 2015-05-04
      • 2018-07-23
      相关资源
      最近更新 更多