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

Incorporating JavaScript to dynamically load an HTML page into an iframe

I am attempting to have each option load a unique page within a frame <!DOCTYPE html> <html> <head> <script> function selectCountry() { var mylist=document.getElementById("country"); document.getElementById("frame").src=mylist.opti ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...

Trying to modify the chosen option while filtering an ajax source using select2?

I am currently integrating the select2 library within a Bootstrap 4 modal in the following manner: <div class="form-group" id="fg-jbInd"> <label for="jbIndustry" class="control-label"gt;Industry * <sele ...

Broadcast and listen to events in AngularJS using `$rootScope.$emit`

I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't load ...

I am encountering the issue where Prisma client python consistently notifies me that my client has not been generated, despite the fact that I have already executed the necessary

After setting up Prisma Client Python and SQLite to create a database for my program successfully, I encountered an issue when trying to run my program. Despite ensuring that everything was installed correctly and running commands like "prisma generate" an ...

Storing the information received from an API as an HTML element

My HTML file contains JavaScript, along with a URL that displays data retrieved from an AWS lambda API call via AWS API Gateway. The page initially appears blank and the data is structured like this: [ {"user": "bob", "groups": ["bobsGroup"], "policies": ...

Is getStaticProps relevant in a CRUD application when using NextJS?

Here's a simple question I've been pondering. I've been exploring the different ways of data fetching in NextJS to really understand their implications. So, in production mode, Static Site Generation occurs at build time, which means we alw ...

Exploring Angular: Techniques for searching within nested arrays

I am looking for a function that can search and filter the largest value in a nested array, and then return the parent scope. Here is an example of my array: data = {"people": [{"male": [ {"name": "Bob" ,"age": "32"}, {"name":"Mike", "age ...

Having trouble with the ajax cache not working properly when trying to load an image

I am attempting to dynamically load an image from the server every time a button is clicked using a GET request. However, I am facing an issue where the cached image is being loaded instead of the latest version. Below is the code I am currently using: & ...

Prevent the resizing of my website on iOS devices using HTML and CSS

I'm encountering an issue with a website I developed that seems to be resizable on certain iOS devices, including the new iPhone X. I haven't been able to replicate this behavior on other standard websites. Perhaps there's a simple CSS solut ...

`Is there a way to repurpose generic type?`

For instance, I have a STRING type that is used in both the test and test2 functions within the test function. My code looks like this: type STRING = string const test = <A = STRING>() => { test2<A>("0") } const test2 = <B& ...

byte sequence displays as binary data (angular + express)

I've been working on pulling files from a back-end Node.js / Express server and displaying them in an Angular front-end. Despite trying different methods, I keep facing the same issue - the data displayed at the front-end appears as a bytestring. Even ...

Utilizing TypeScript with dc.js for enhanced data visualization capabilities

I've encountered an issue with types while working with dc.js version 4.2.7. To address this, I went ahead and installed what I believe to be the standard types module for dc.js using the following command: Command I used for Installation npm i @type ...

React is throwing an error that says, "You cannot use the import statement outside a

My journey with learning React has just begun. I followed the steps outlined in the starting guide at https://react.dev/learn/add-react-to-an-existing-project, but unfortunately, I encountered an error: "Cannot use import statement outside a module." Here ...

I am confused as to why my function is selecting all the checkboxes when it should only be selecting one

I am facing an issue while creating a list with checkboxes in reactJS. Whenever I click on a single checkbox, all the checkboxes get selected instead of just the one that was clicked. How can I resolve this problem? const checkHandler = () => { if ( ...

Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds. In addition, th ...

Restrict Recursive GraphQL Schema Query Depth with graphql-sequelize resolver in Node.js using express-graphql

In my code, I have two models called User and Post. My goal is to retrieve User information when querying a post, as well as obtain all of a User's posts when querying a user. These two models are associated in the following manner: User.hasMany(Pos ...

Is it possible to place an open div panel between two tweets?

I'm in the process of developing a UI with Twitter feeds. I want to create a feature where a panel can be opened between two tweets, causing the tweet below to shift downwards. This function is commonly seen in tweet clients like TweetBot; as each new ...

Create an additional data field in an existing resource using the PUT method

Incorporated Google authentication into my NextJS application. The process involves the user making progress within the web app, which is stored in local storage as an array. If the user decides to register, I receive the session back and then send a PUT r ...

Can you help me understand how to create a JSON file using webpack?

My goal is to create a customized `manifest.json` file for Chrome extensions in a more efficient, programmatic manner. Utilizing npm for dependency management, I've noticed that the `package.json` shares key fields with the `manifest.json`, such as "n ...