0

I'm trying to use Prisma with ValidationPipe that NestJS provides but it is not working, I was using class-validator package with DTO's (classes) as ValidationPipes and it was working fine, now I need a way to use the same pattern with Prisma without the need of DTOs to not have duplicated types. (I want to avoid creating custom pipes for validation)

DTO FILE:

import { IsNotEmpty } from 'class-validator';

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

  @IsNotEmpty()
  description: string;
}

WITH DTO: working

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

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

WITH PRISMA: not working

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

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

full code repo link

SebMaz93
  • 539
  • 1
  • 6
  • 14
  • 1
    DTOs and Data models are 2 different things. What the user input and send to your API don't necessarily match what you have in the database. And coupling the form input with a database table is a bad practice overall as it will prevent you from changing one without the other. – Eric Jeker Jun 25 '21 at 07:25

1 Answers1

2

Nest's ValidationPipe works by default by using class-validator and class-transformer, and classes for the DTO. Without the class having these libraries' decorators, the pipe won't do anything for you. You'd need some way to tell Prisma to generate class types that relate to the SDL with the class-validator decorators, which at this moment I don' think is possible.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • yes got it, thanks. I've found [this lib](https://github.com/MichalLytek/typegraphql-prisma) its kinda doing something similar but i think it will not work since editing the schema and regenerating class types will override my validations on the class. – SebMaz93 May 23 '21 at 00:38