【发布时间】: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