typescriptnestjsprismadtoclass-validator

NestJS and Prisma, do we really need DTOs for validation when we could use Prisma Generated Type?


I m building a NestJS project using Prisma ORM, and after some tutorial and check on the subject, I don't see (or seem to understand) the use of DTO here, when we could use the Prisma Generated Type

It's seems to be a duplication of what we already did in the Prisma Schema, and could lead to bad update later as we will have to update both the schema and the DTOs

After some search on it I come to the solution to directly use the Prisma Generated Type (as UserCreateInput / UserGetPayload)

here is the code that I did :

users.interface.ts

import { type Prisma } from "@prisma-postgresql";

// select for query filtering
export const UsersSelect = {
    name: true,
    email: true,
} satisfies Prisma.UsersSelect;
// UsersGetPayload is autogenerated by prisma after migration
export type Users = Prisma.UsersGetPayload<{ select: typeof UsersSelect }>;

users.service.ts

import { Injectable } from "@nestjs/common";

// prisma import
import { PrismaPostgresqlService } from "../../prisma/services/prisma-postgresql.service";
import { Users, UsersSelect } from "../interfaces/user.interface";

@Injectable()
export class UserService {
    private prismaSQL;

    constructor(prismaSQL: PrismaPostgresqlService) {
        this.prismaSQL = prismaSQL;
    }

    async findAll(): Promise<Users[]> {
        return await this.prismaSQL.users.findMany({
            select: UsersSelect,
        });
    }
}

with this I can have my own type coming directly from prisma

I don't know if it's indeed a good solution or not, maybe I m missing the point of DTOs here ?

Why would it be a good idea to still use DTOs in my case ? or is this a good solution ?


Solution

  • To resume for people coming by here, actually the only use case for DTOs with Prisma is for Swagger

    You can't annotate Prisma Generated Type with the Swagger decorator, so if you want your documentation to be clear and complete, you will have to use DTOs until Prisma integrate this feature

    Actually there is a way to make DTOs fast and without risk until this feature come out

    1. use a Prisma DTOs generator tools : https://github.com/vegardit/prisma-generator-nestjs-dto

    2. use the Swagger CLI integrated in your nestjs project to handle the decorator : https://docs.nestjs.com/openapi/cli-plugin

    I think it's the best way of handling this until Prisma add this feature