EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data.
While building my Next.js app using Prisma to connect to the DB, I'm facing challenges with the auto-generated Typescript definitions.
Despite following the documentation, I'm struggling to figure out how to select a subset of fields from Post
. Take this example from the docs:
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>
Consider a simplified version of 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
}
I aim to exclude certain auto-generated fields from the Post
type, such as createdAt
. Essentially, the user.posts[0]
type should contain all fields except createdAt
.
One approach 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[]
}
However, I am looking for a cleaner solution. Are there any alternatives?