简体   繁体   中英

Prisma: how to exclude properties from generated types

EDIT there's a hidden danger in hiding fields in the TS definitions: the fields will not be accessible during development with intellisense, but the full object with "hidden" fields can be accidentally sent in a response, potentially exposing sensitive data.

I'm building my app using Prisma to connect to the DB (Next.js app). I'm having some trouble with the auto generated Typescript definitions.

I'm following the docs but I can't figure out how to select a subset of fields from Post . In their example:

import { Prisma } from '@prisma/client'

const userWithPosts = Prisma.validator<Prisma.UserArgs>()({
  include: { posts: true }, // -> how can I exclude some fields from the Post type?
})

type UserWithPosts = Prisma.UserGetPayload<typeof userWithPosts>

Imagine Post being as follows (simplified):

model Post {
  id         Int        @id @default(autoincrement())
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   Int
}

I'd like to exclude some of the auto-generated fields from the Post type, for example createdAt . Basically user.posts[0] type will have all the fields except createdAt .

One solution could be:

const postData = Prisma.validator<Prisma.PostArgs>()({
  select: { id: true, title: true, published: true, authorId: true }
})

type UserWithPosts = Omit<Prisma.UserGetPayload<typeof userWithPosts>, 'posts'> & {
  posts: postData[]
}

But I was hoping for something a bit cleaner. Any alternatives?

I found a solution: instead of using include use select with a nested select for posts . The problem is that it becomes quite verbose and cumbersome to maintain (every time a field is added on the schema it must be added here as well...)

const userWithPosts = Prisma.validator<Prisma.UserArgs>()({
  select: {
    email: true,
    name: true,
    posts: {
      select: {
        id: true,
        title: true,
        published: true,
        authorId: true
      }
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM