What could be causing the problem between typescript and Prisma ORM as I attempt to locate a distinct item?

I'm encountering a problem with using the prisma .findUnique() function. Even though my code doesn't display any compilation errors, attempting to access a product page triggers a runtime error.

PrismaClientValidationError: 
Invalid `prisma.product.findUnique()` invocation:

{
  where: {
    id: "6"
        ~~~
  }
}

Argument `id`: Invalid value provided. Expected Int, provided String.

Despite using the product id as an int, it seems that .findUnique() is interpreting it as a string. Can anyone suggest a solution to make .findUnique() function correctly?

Here is my schema.prisma file displaying the schema:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Product {
  id          Int      @id @default(autoincrement())
  name        String   @db.VarChar(127)
  description String   @db.VarChar(511)
  imageUrl    String   @db.VarChar(255)
  price       Int      @db.SmallInt
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@map("products")
}

This is the section where I attempt to find an item by its id:

interface ProductPageProps {
  params: {
    id: number;
  };
}

const getProduct = cache(async (id: number) => {
  const product = await prisma.product.findUnique({ where: { id } });
  if (!product) notFound();
  return product;
});

export async function generateMetadata({
  params: { id },
}: ProductPageProps): Promise<Metadata> {
  const product = await getProduct(id);

  return {
    title: product.name + "Project",
    description: product.description,
    openGraph: {
      images: [{ url: product.imageUrl }],
    },
  };
}

export default async function ProductPage({
  params: { id },
}: ProductPageProps) {
  const product = await getProduct(id);
  return (
    <div className="flex flex-col gap-4 lg:flex-row lg:items-center">
      <Image
        src={product.imageUrl}
        alt={product.name}
        width={400}
        height={400}
        className="rounded-lg"
        priority
      />
      <div>
        <h1 className="text-5xl font-bold">{product.name}</h1>
        <PriceTag price={product.price} className="mt-4" />
        <p className="py-6">{product.description}</p>
      </div>
    </div>
  );
}


I have attempted converting the number to a string and passing it into .findUnique() just to test if it needs to be a string:

 const stringId = id.toString();
 const product = await prisma.product.findUnique({ where: { stringId } });

However, this gives me an error:

Object literal may only specify known properties, and 'stringId' does not exist in type 
'ProductWhereUniqueInput'.ts(2353)

index.d.ts(1548, 5): The expected type comes from property 'where' which is declared
 here on type '{ select?: ProductSelect<DefaultArgs> | null | undefined; where: ProductWhereUniqueInput; }'

It appears to be a type error, and I'm unsure how to resolve it. Any suggestions on how to tackle this issue would be appreciated.

Answer №1

To successfully pass the ID, follow this example:

const item = await database.query.findUnique({ where: { id: +id } });

Implementing this should make things run smoothly.

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

The proper method for referencing TypeScript compiled files with the outDir option

I am currently working on a simple app that consists of two .ts files. These files are compiled using the following tsconfig.js file: { "compilerOptions": { "target": "ES5", "module": "commonjs", "sourceMap": true, "emitDecoratorMetadata ...

Extracting data from a JSON object using Angular 2

I need advice on the most efficient way to handle JSON within my angular2 application. The JSON data I am working with includes: { "rightUpperLogoId": { "id": 100000, "value": "" }, "navbarBackgroundColorIdCss": { "id" ...

Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption. There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, rec ...

How to retrieve the default type returned by a function using a custom TypeMap

I have a function that returns a promise with a type provided by generics. const api = <Model>(url: string) => Promise<Model> Currently, I always need to set the type of the returned data. const data = await api<{id: string, name: string ...

Error Encountered (TypeError): Unable to access attributes of undefined (attempting to read 'appendChild')

I have been working on creating a choropleth Map of AntV using React.js with functional components. This is the code snippet for my chart: import DataSet from '@antv/data-set'; import { Chart } from '@antv/g2'; const CustomerByRegion = ...

Encountering difficulty invoking a component method from d3's call() function

My current setup involves using D3 to drag and drop links in the following manner: .call(d3.drag() .on("start", linkDragStart) .on("drag", linkDragging) .on("end", linkDragEnd)); Recently, I decided to extract this functionality into a separate met ...

Encountering build issues in my next.js application post updating to version 12.#.# and implementing Typescript

In my next.js application, I recently upgraded to version 10 and added TypeScript to the mix. Despite ironing out all issues during development, I encountered errors when running yarn next build due to my use of the keyword interface. ./src/components/ ...

Issue encountered with ng-include compatibility in Angular 5

Just getting started with Angular and working on a small test project using Angular 5 and Visual Code. I'm attempting to use ng-include but the template is not displaying. src add-device add-device.component.html add-device.com ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Using TypeScript gives you the ability to specify the type of an object while destructuring it,

Currently in the process of refactoring a NodeJS application to TypeScript. I have been consistently using object destructuring and have also been creating aliases while object destructuring, as shown in the code block below. My question is, how can I sp ...

Alter the class based on the incoming string from the rxjs stream

I have a stream that outputs strings, and based on these strings I want to apply certain classes to a specific tag: If the string is "ok", add class "fa-check" If the string is "loading", add classes "fa-spin" and "fa-spinner" If the string is "error", a ...

Exploration of narrowing union types in React with TypeScript

import { Chip } from "@mui/material"; type CourseFilterChipsRangeType = { labels: { from: string; to: string }; values: { from: number; to: number }; toggler: (from: number, to: number) => void; }; type CourseFilterChipsCheckType = { ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

Unleashing the Power of Typescript and SolidJS: Expanding the Properties of JSX Elements

Is there a way to enhance the props of an existing JSX element in SolidJS and craft a custom interface similar to the ButtonProps interface shown in this React example below? import Solid from 'solid-js'; interface ButtonProps extends Solid.Butt ...

When trying to use TypeScript with next.js, encountering an unexpected token `?` error is not

Having an issue with next.js, the command npm run dev keeps failing due to a syntax error related to an optional property in a tsx file: Syntax error: Unexpected token 44 | 45 | type State<T_HT> = { > 46 | ghostHighlight: ?{ | ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

What is the best way to pass updates from input model class in a child component to its parent in Angular 13?

What is the best way to propagate changes in the input model class from a child component to its parent in Angular 13? Child Component export class ChildComponent implements OnInit { @Input() mdlInData: any; @Output() mdlOutData = new EventEmitter< ...

Mastering Typescript generics for accurate mapping between keys and values through indirection

I've been struggling to understand how to create a specialized mapper that can indirectly map methods based on one object's values corresponding to another object's keys. The mapper used in the code snippet below is not mine; it's an e ...

The type definition file for 'bson' could not be located. It appears to be missing from the program due to being the entry point for the implicit type library 'bson'

I recently set up a new Typescript/React project and encountered the following error in the tsconfig.json file: "Cannot find type definition file for 'bson'. The file is in the program because: Entry point for implicit type library 'bson&ap ...