【问题标题】:Prisma: how to exclude properties from generated typesPrisma:如何从生成的类型中排除属性
【发布时间】:2021-12-20 10:52:22
【问题描述】:

编辑 在 TS 定义中隐藏字段存在一个隐患:在开发过程中使用智能感知将无法访问这些字段,但带有“隐藏”字段的完整对象可能会意外发送到响应中,从而可能暴露敏感数据。

我正在使用 Prisma 构建我的应用程序以连接到数据库(Next.js 应用程序)。我在使用自动生成的 Typescript 定义时遇到了一些问题。

我正在关注the docs,但我不知道如何从Post 中选择字段子集。在他们的例子中:

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>

想象Post 如下(简化):

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
}

我想从Post 类型中排除一些自动生成的字段,例如createdAt。基本上user.posts[0] 类型将包含除createdAt 之外的所有字段。

一种解决方案可能是:

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[]
}

但我希望有一些更清洁的东西。有其他选择吗?

【问题讨论】:

    标签: javascript typescript next.js prisma


    【解决方案1】:

    我找到了一个解决方案:不要使用 include,而是使用 select 和嵌套的 select for posts。问题是它变得非常冗长和维护起来很麻烦(每次在架构上添加一个字段时,它也必须在这里添加......)

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

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 2022-08-22
      • 2011-07-07
      • 2022-08-21
      • 2016-10-29
      相关资源
      最近更新 更多