Error encountered when utilizing cursor in Prisma

I am currently utilizing Prisma version 4.2.1 within a Next.js API Route to implement cursor-based pagination for posts.

Upon passing the cursor to the API endpoint, I encounter an error message (500) in the console:

TypeError: Cannot read properties of undefined (reading 'createdAt')
    at getPost (webpack-internal:///(api)/./lib/api/post.ts:67:46)
error - TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received an instance of TypeError

To access the API endpoint, I utilize Postman.

If I remove the cursor from the API Route, the errors disappear and the posts are returned correctly.

Although I have attempted various solutions including upgrading to Prisma version 4.2.1, using .toString() on the cursor, and modifying the AllPosts interface to 'any', I have been unsuccessful in resolving the TypeError.

Could someone guide me on rectifying this error and successfully having Prisma acknowledge the cursor as valid?

API Route

import prisma from "@/lib/prisma";
import type { NextApiRequest, NextApiResponse } from "next";
import type { Post, Site } from ".prisma/client";
import type { Session } from "next-auth";
import { revalidate } from "@/lib/revalidate";
import type { WithSitePost } from "@/types";

interface AllPosts {
  posts: Array<Post>;
  site: Site | null;
}

export async function getPost(
  req: NextApiRequest,
  res: NextApiResponse,
  session: Session
): Promise<void | NextApiResponse<AllPosts | (WithSitePost | null)>> {
  const { postId, siteId, published, cursor } = req.query;

  if (
    Array.isArray(postId) ||
    Array.isArray(siteId) ||
    Array.isArray(published) ||
    Array.isArray(cursor)
  )
    return res.status(400).end("Bad request. Query parameters are not valid.");

  if (!session.user.id)
    return res.status(500).end("Server failed to get session user ID");

  try {
    if (postId) {
      const post = await prisma.post.findFirst({
        where: {
          id: postId,
          site: {
            user: {
              id: session.user.id,
            },
          },
        },
        include: {
          site: true,
        },
      });

      return res.status(200).json(post);
    }

    const site = await prisma.site.findFirst({
      where: {
        id: siteId,
        user: {
          id: session.user.id,
        },
      },
    });

    const posts = !site
      ? []
      : await prisma.post.findMany({
          take: 10,
          skip: cursor === undefined ? 0 : 1,
          cursor: {
            id: cursor,
          },
          where: {
            site: {
              id: siteId,
            },
            published: JSON.parse(published || "true"),
          },
          orderBy: {
            createdAt: "desc",
          },
        });

    const lastPostInResults = posts[9];
    const nextCursor = lastPostInResults.createdAt;

    return res.status(200).json({
      posts,
      site,
      nextCursor,
    });
  } catch (error) {
    console.error(error);
    return res.status(500).end(error);
  }
}

Prisma Schema

model Post {
  id            String   @id @default(cuid())
  title         String?  @db.Text
  content       String?  @db.LongText
  slug          String   @default(cuid())
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
  published     Boolean  @default(false)
  site          Site?    @relation(fields: [siteId], references: [id], onDelete: Cascade)
  siteId        String?

  @@unique([id, siteId], name: "post_site_constraint")
}

model Site {
  id            String        @id @default(cuid())
  name          String?
  createdAt     DateTime      @default(now())
  updatedAt     DateTime      @updatedAt
  user          User?         @relation(fields: [userId], references: [id])
  userId        String?
  posts         Post[]
}

Answer №1

By including the @unique attribute to the Post model, implementing the necessary schema modifications, and running prisma generate, this issue was successfully resolved.

model Post {
  createdAt     DateTime @default(now())
  ...
}

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

Export problem in TypeScript

I'm having trouble with exporting in the prisma TypeScript file while executing it within a Node.js GraphQL project. Here is the error I am encountering: 05-12-2018 18:20:16: SyntaxError: /home/user/Publish/PracticeBusiness/src/generated/prisma.ts: ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Creating a flexible TypeScript function handler that accepts optional arguments depending on the function's name

I am facing a challenge with defining the function type for running helper functions that prepare database queries. Some of these functions have arguments, while others do not. TS Playground Link type PreparedQuery = { query: string; params?: string[] ...

Implement Angular backend API on Azure Cloud Platform

I successfully created a backend API that connects to SQL and is hosted on my Azure account. However, I am unsure of the steps needed to deploy this API on Azure and make it accessible so that I can connect my Angular app to its URL instead of using loca ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

What is the reason that the router is not functioning correctly when using router.push({pathname: 'somewhere', query: {id: 1234}}) on the application router?

Is it possible to modify the route.query in a Next.js app directory based on the documentation I came across? 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams ...

Tips for monitoring and automatically reloading ts-node when there are changes in TypeScript files

I'm experimenting with setting up a development server for my TypeScript and Angular application without having to transpile the .ts files every time. After some research, I discovered that I am able to run .ts files using ts-node, but I also want th ...

Retrieve data from a JSON object within an HTML document

How do I display only the value 100 in the following div? <div> {{uploadProgress | async | json}} </div> The current displayed value is: [ { "filename": "Mailman-Linux.jpg", "progress": 100 } ] Here is my .ts file interface: interface IU ...

The property xyz is not found in the type 'IntrinsicAttributes & interface abc'

I have an array of objects structured like this: const data = { "Large_Plates": [ { "name": "Cauliower/ Shanghai Fried rice with stir fry vegetables", "id": "1", "price_Veg&quo ...

Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have: <form [formGroup]="myForm" (ngSubmit)="onSubmitted()"> <app-names></app-names> <app-address> ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

Enhance your Vuex action types in Typescript by adding new actions or extending existing

I'm new to Typescript and I'm exploring ways to add specific type structure to all Actions declared in Vue store without repeating them in every Vuex module file. For instance, instead of manually defining types for each action in every store fi ...

Issue with rendering React Toastify

I'm running into an issue while trying to integrate react toastify into my react vite application. Specifically, I keep getting an error related to useSyncExternalStore even after attempting to switch to version 9 of react toastify. My React version i ...

Exploring the Integration of OverlayScrollbars with TypeScript

Currently, I am delving into TypeScript utilizing a project built on ASP.NET Core 3.0 and the VS 2019 IDE. Recently, I acquired the OverlayScrollbars plugin via npm: . npm install overlayscrollbars npm install @types/overlayscrollbar Provided below is a ...

Is there a method to lower the hosting of my Next.js website on Vercel?

If I happen to want to temporarily take down my website for some reason, is it possible to do this easily using Vercel? Or would it be better to handle it through my domain registrar (Namecheap) or perhaps utilize an add-on for my app (Next.js)? I'm ...

How can I resolve the issue of "store.getstate is not a function" in Next.js version 13?

I encountered an issue with the following error message: Next.js is up to date Unhandled Runtime Error Error: store.getState is not a function "use client"; import { configureStore } from "@reduxjs/toolkit"; import productSlice from & ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...