如何在 NestJS 中使用 Prisma 和 ValidationPipe?

问题描述 投票:0回答:2

我正在尝试将 Prisma 与 NestJS 提供的 ValidationPipe 一起使用,但它不起作用,我使用带有 DTO(类)的

class-validator
包作为
ValidationPipes
并且它工作正常,现在我需要一种方法来使用相同的使用 Prisma 的模式不需要 DTO 就没有重复的类型。 (我想避免创建自定义管道进行验证)

DTO文件:

import { IsNotEmpty } from 'class-validator';

export class TodoCreateDto {
  @IsNotEmpty()
  title: string;

  @IsNotEmpty()
  description: string;
}

使用 DTO: 工作

@Controller('todos')
export class TodosController {
  constructor(private todosService: TodosService) {}

  @Post()
  @UsePipes(ValidationPipe)
  createTodo(@Body() todoCreateDto: TodoCreateDto) {
    return this.todosService.createTodo(todoCreateDto);
  }
}

使用 PRISMA: 不工作

@Controller('todos')
export class TodosController {
  constructor(private todosService: TodosService) {}

  @Post()
  @UsePipes(ValidationPipe)
  createTodo(@Body() todoCreateInput: Prisma.TodoCreateInput) {
    return this.todosService.createTodo(todoCreateInput);
  }
}

完整代码回购链接

validation nestjs prisma class-validator prisma2
2个回答
2
投票

Nest 的

ValidationPipe
默认使用
class-validator
class-transformer
,以及 DTO 的类。如果类没有这些库的装饰器,管道将不会为您做任何事情。您需要一些方法来告诉 Prisma 使用类验证器装饰器生成与 SDL 相关的类类型,目前我认为这是不可能的。


0
投票

Nestjs 有一个样本库,我认为样本 22 有办法做到这一点,看看那里的自述文件,你会看到诀窍 https://github.com/nestjs/nest/tree/master/sample/22-graphql-prisma

© www.soinside.com 2019 - 2024. All rights reserved.