Prisma Hack: excluding properties in type generation

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?

Answer №1

After some experimentation, I came across a different solution: instead of utilizing include, I switched to using select along with a nested select for the entity posts. However, this approach can become verbose and burdensome to maintain over time (as any new field added to the schema needs to be included here as well...)

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show the React component once the typewriter effect animation is complete

Hello there, I am looking to showcase my social links once the Typewriter effect finishes typing out a sentence in TypeScript. As someone new to React, I'm not quite sure how to make it happen though. Take a look at the code snippet below: ` import ...

Is it possible to adjust the color of the iOS status bar using NativeScript, Angular 2, and TypeScript?

I recently came across this npm package called NativeScript Status Bar, available at the following link: https://www.npmjs.com/package/nativescript-statusbar However, I'm facing an issue because I cannot use a Page element as I am working with Angul ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Error message: There appears to be a type error within the labelFunc of the KeyBoardDatePicker component in the Material-UI

I am currently working with a material-ui pickers component: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant='inline' inputVariant=& ...

Exploring Javascript/JQuery parameters based on data types

I'm a bit confused about whether the title accurately reflects my question. I need help understanding how jQuery deals with functions that are called with different argument combinations, such as ("Some String", true, function(){}) and ("Some String", ...

Having trouble retrieving the user-object within tRPC createContext using express

I'm encountering an issue with my tRPC configuration where it is unable to access the express session on the request object. Currently, I am implementing passport.js with Google and Facebook providers. Whenever I make a request to a regular HTTP rout ...

Installing external Javascript libraries on Parse cloud code can be done by following these steps

Currently, I have integrated these JavaScript libraries into my Parse cloud code. var request = require('request'); var fs = require('fs'); var Twit = require('twit'); However, the code refuses to compile if these libraries ...

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

Guide to deploying a NextJS app on the address 0.0.0.0:3000 using nrwl/next instead of the default localhost:3000 address

I am attempting to deploy my application on 0.0.0.0:3000 instead of localhost. Each time I execute the command nx serve career --port=3000 --host=0.0.0.0 The application is being hosted on: tcp6 0 0 :::3000 :::* ...

Is it possible to select multiple drop-down lists on a webpage using Python and Selenium?

I am encountering an issue while attempting to click on multiple dropdown lists within a page. I continuously receive an error message stating that my list object does not have an attribute 'tag_name'. Here is my code snippet: def click_follow_ ...

Changing the selection on multiple input fields in Angular

I am working with two select elements in my form. Based on the selected value from the first select, I am filtering data for the second select. Additionally, I have an option to add the same row of form if desired. My issue is that when I select a value fr ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...

Leveraging a specialized Angular filter as a cellFilter within the columnDefs of ui-grid, set in an Angular constant

In my Angular application called myApp, I have a unique filter named myFilter. Additionally, I am utilizing UI Grid to display data in multiple grids such as myGrid1 and myGrid2. To streamline the process, I have organized column definitions for these grid ...

The Vue CLI build is displaying a blank page when hosted on an Apache server

I encountered an issue with vue cli. Running npm run serve went smoothly, but when I tried dev mode using npm run build-dev, the build process finished with a blank page displayed. The error message received was "Uncaught SyntaxError: Unexpected token &ap ...

Steps to make a pop-up window for text copying by users

On my website, I have a link that users need to copy for various purposes. I want to provide an easy way for them to see the link and then manually copy it to their clipboard. Instead of using code to copy to the clipboard, I am looking for a solution whe ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...