utilizing dynamic sorting with typed queries in prisma

I'm currently facing an issue while attempting to define a query in prisma dynamically. I encountered a roadblock right at the beginning of the process.

Here's a piece of code that works:

const items = await prisma.styleTags.findMany({
    orderBy: {
        name: 'asc',
    }
});

However, when I try to define the query separately, I run into TypeScript errors.

const orderBy = {
    cname: 'asc',
}
const items2 = await prisma.styleTags.findMany({
    orderBy
});

On the surface, these two approaches should be identical. But somewhere within Prisma's complex web of auto-generated code...

Type '{ cname: string; priority: string; }' is not assignable to type 'Enumerable<StyleTagsOrderByWithRelationInput> | undefined'.
  Type '{ cname: string; priority: string; }' is not assignable to type 'StyleTagsOrderByWithRelationInput'.
    Types of property 'cname' are incompatible.
      Type 'string' is not assignable to type 'SortOrder | undefined'.

The error message

Type 'string' is not assignable to type 'SortOrder | undefined'
prompted me to try passing orderBy: 'name', but that also failed.

For what it's worth, using @ts-ignore makes the code work. However, if Prisma's typechecking needs to be overridden, then its purpose becomes somewhat redundant.

My plan next is to attempt dynamically composing the orderBy based on passed parameters. But first, I need to resolve the issues mentioned above.

Can anyone shed light on why this typechecking issue with Prisma occurs?

Answer №1

Here are some clever solutions you can try:

  1. To prevent TypeScript from inferring the order as a string, wrap the orderBy with as const.
  2. Instead of using "asc," consider using Prisma.orderBy.asc.

Answer №2

This is the logic behind my NextJs API endpoint:

import type { NextApiRequest, NextApiResponse } from 'next';
import prisma from '@/lib/prisma';

export default async function handleRequest(req: NextApiRequest, res: NextApiResponse) {
    const { _page, _limit, _sort, _order} = req.query;
    const limit = +(_limit ?? 20);
    const offset = (+(_page ?? 1) -1 ) * limit;
    const sort = (_sort ?? 'id').toString();
    const order = _order ?? 'asc';

    const orderBy = {[sort]: order};
    const userCount = await prisma.users.count();
    const users = await prisma.users.findMany({
        orderBy,
        skip: offset,
        take: limit
    });

    res.setHeader('Content-Type', 'application/json');
    res.setHeader('x-total-count', userCount);
    res.status(200).json(users);
}

I trust this information will be beneficial.

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

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

Using Angular with THREE JS integration in Javascript

I am currently experimenting with Angular and facing a challenge that I can't seem to figure out. The issue I am encountering involves integrating a javascript code, SunLight.js, from the repository https://github.com/antarktikali/threejs-sunlight in ...

Creating a personalized Typescript type declaration for a npm package in a Create React App

I'm having trouble incorporating a type declaration for the react-load-script package in my Create React App project. To address this, I created a file named react-load-script.d.ts within the src directory and included the following code: // Type de ...

Error encountered while running npm run build in the Dockerfile build process

I'm currently in the process of dockerizing a node application that utilizes typescript. Here is my Dockerfile: FROM node:14 as builder ENV NODE_ENV=production WORKDIR /usr/app COPY package*.json ./ RUN npm install -g example@example.com RUN npm i CO ...

Is it better to retrieve data on the server side or client side in order to fill a select element in a Next.js form?

Currently, I am in the process of developing a web system with Next 13 where I am faced with a dilemma when it comes to populating a select element. The select element needs to be populated with data from my database, but it is within a client-side form t ...

Global variable is null in Protractor test when utilized in separate class

I have a TypeScript class where I declared a global variable and used it in a method of the same class. Here is an example: First TypeScript Class: export class FirstTestDetails { baseProductDetails = { baseQty: null, basePrice: null, ...

Employing Bazel in conjunction with Lerna and Yarn workspaces

It seems that a lot of people are currently utilizing lerna and/or yarn workspace. I'm thinking about either transitioning from them to Bazel, or perhaps integrating them with Bazel in conjunction with an example project for guidance. Take for insta ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Implementing try-catch logic for element visibility in Playwright using TypeScript poses limitations

There is a specific scenario I need to automate where if the title of a page is "Sample title", then I must mark the test as successful. Otherwise, if that condition is not met, I have to interact with another element on the page and verify if the title ch ...

Retrieve Data using Axios and Save in Interface with Multiple Arrays in TypeScript

Hey everyone, I'm facing an issue when trying to make a GET request using Axios through an API. When I try to assign the selected data from Axios to the userDetail interface, it gives me an error. Please take a look at the Code Sandbox where I have in ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

Create a personalized button | CKEditor Angular 2

I am currently working on customizing the CKEditor by adding a new button using the ng2-ckeditor plugin. The CKEditor is functioning properly, but I have a specific requirement to implement a button that will insert a Rails template tag when clicked. For ...

The types definition for OpenSeadragon is lacking a property

I have developed an application using React Typescript and have integrated OpenSeadragon () for displaying images. To incorporate type definitions for OpenSeadragon, I am utilizing @types/openseadragon: https://www.npmjs.com/package/@types/openseadragon M ...

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Distinguishing Literal and Parameterized Routes in Angular 6

I've encountered a strange issue that I'm not sure how to handle. In my application, you can either view your public account or create a new one. The Account and CreateAccount modules are standalone and lazy loaded in the routes.ts file. export ...

Tips for avoiding multiple reference paths in Angular TypeScript: - Simplify your imports

Setting up Typescript for an Angular 1.5 application has been a bit of a challenge. To ensure that a TS file can be compiled by gulp without any errors, I have to include the following line: ///<reference path="../../../../typings/angularjs/angular.d.t ...

Generate a Jest dummy for testing an IncomingMessage object

I am facing a challenge in writing a unit test for a function that requires an IncomingMessage as one of its parameters. I understand that it is a stream, but I am struggling to create a basic test dummy because the stream causes my tests to timeout. : T ...

Ways to update the value within an object in an array stored in a BehaviorSubject?

My initial data is: const menuItems = [{id: 1, active: false}, {id: 2, active: false}] public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems); public menu$ = this.menuSubject$.asObservable(); I am attempting to update the element with ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Tips for efficiently deconstructing JSON arrays, objects, and nested arrays

I'm attempting to destructure a JSON file with the following structure: [ { "Bags": [ { "id": 1, "name": "Michael Kors Bag", "price": 235, "imgURL" ...