Reputation: 2503
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?
Upvotes: 2
Views: 3404
Reputation: 2503
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
}
}
}
})
Upvotes: 0