Ways of utilizing a dynamic key for invoking a resource from prisma

Currently, I am attempting to implement a more general method to retrieve data from Prisma. The function in question appears as follows:

import { Prisma, PrismaClient } from '@prisma/client';
import { NextApiRequest, NextApiResponse } from 'next';

const prisma = new PrismaClient();

const getAllOfResource = async (resourceName: Prisma.ModelName) => {
  const resource = prisma[resourceName as Prisma.ModelName];
  if (!resource.findMany) throw Error('Error: findMany not found, does resource exist?');
  return await resource.findMany();
};

const validateResourceTypeExists = (resourceType: unknown): resourceType is Prisma.ModelName => {
  return typeof resourceType === 'string' && Object.keys(Prisma.ModelName).includes(resourceType);
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const requestedResource = req.query.id;
  if (!validateResourceTypeExists(requestedResource)) {
    res.status(500).json({
      message: 'Please use a valid resource type',
    });
  } else {
    const resource = await getAllOfResource(requestedResource);
    return res.status(200).json(resource);
  }
}

Nevertheless, an error occurs when invoking the findMany() on the resource:

This expression is not callable.
  Each member of the union type '(<T extends mediaFindManyArgs<DefaultArgs>>(args?: SelectSubset<T, mediaFindManyArgs<DefaultArgs>> | undefined) => PrismaPromise<...>) | (<T extends booksFindManyArgs<...>>(args?: SelectSubset<...> | undefined) => PrismaPromise<...>)' has signatures, but none of those signatures are compatible with each other

I cannot pinpoint the reason for this issue, given that any item within Prisma.ModelName should possess the findMany method. Is there perhaps a different type that I overlooked or could there be a fundamental flaw in my approach?

After experimenting with a few options, it seems likely that my lack of comprehension regarding the process is causing this problem.

Answer №1

In certain situations, TypeScript may not be able to ensure that the resource includes the "findMany" method, which can lead to an exception occurring. To avoid this issue, you can specify the type of the resource beforehand:

const resource: Prisma.PrismaClient['resourceName'] = prisma[resourceName as Prisma.ModelName];

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

Best practices for applying the Repository pattern within a NestJS application

After reviewing the NestJS documentation and examining their sample source codes, it appears challenging to implement a Repository pattern between the service layer and the database layer (e.g. MongoDB). In NestJS, database operations are executed directl ...

Having trouble with Next.js and Next-auth? When I make an HTTP request in getServerSideProps, getSession is returning null in my secured API Route

I am currently working on securing an API Route that is being called from both the Client and Server-side on different pages. When accessing the test page, it returns a 401 error. However, when accessing the test2 page, the content is retrieved successfu ...

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

Difficulty in detecting variable modifications during testing - Angular2+

After successful login, I expect a certain variable to be updated with the appropriate value. However, during testing, all I see is 'undefined' returned. This variable does change when interacting with the app, showing an error message like &apo ...

Ways to determine if a specified character sequence is present in an Enumerator?

One of my coding dilemmas involves an enum that looks like this: export enum someEnum { None = <any>'', value1 = <any>'value1', value2 = <any>'value2', value3 = <any>'value3' ...

When utilizing Angular, the mat-datepicker is displayed underneath the modal, even after attempting to modify the z-index

I am encountering a problem with a mat-datepicker displaying below a modal in my Angular application. Here are the key details: Html: <div class="col-12"> <mat-form-field appearance="fill"> <mat-label>Start Date ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

What is the best way to utilize my data with Charts.js for my specific situation?

I am utilizing Charts.js in my Angular project (not AngularJS) and I am trying to create a graphic representation with data from my database that shows the distribution between men and women. However, I am struggling to figure out how to loop through the d ...

Unable to locate the main source for loading

I am facing an issue with my app where I am unable to load a basic component. It seems like a simple problem, but I just can't seem to figure it out. Here is the code for my component: import { Component, OnInit } from '@angular/core'; imp ...

Is it possible to selectively render a page or component in Next.js 13 based on the request method?

Is there a way to conditionally render a page based on the request method in Nextjs 13? For example, when registering a user, can we show a signup form on a get request and display results on a post request? With all components now being server components ...

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

What is the best way to combine a server-side rendered component with a client-side component in Next.js 13?

Our goal is to create a dynamic server-side rendering (SSR) component that can be refreshed by entering text into a search input field. ...

Issue with state not being correctly updated within an asynchronous function of the useEffect hook

Anticipated Outcome: Upon initial rendering, the useEffect function is intended to fetch a series of pool addresses and store them in getPoolsList. This retrieved data should then be used to update the state of poolsList. const [poolsList, setPoolsList] = ...

Is it possible to have a button within a table that, when clicked, opens a card overlaying the entire table?

I'm having an issue with a table and card setup. When I click the button in the table, the card that appears only covers part of the table. I want it to cover the entire table area based on the content inside the card. How can I make this happen? I&a ...

Error: The function (0 , _pages_auth__WEBPACK_IMPORTED_MODULE_3__.registerUser) is invalid and cannot be executed

This is my Auth.js script const submitStudentForm = async (formData) => { const { address ,batchTime, collageName, email, fatherName, gender, guardianMobile, hscBoard, hscGPA, hscPassingYear, hscReg, hscRoll, imgeURL, motherName, name, paymentAmou ...

Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService. When I send the array, the data appears as NULL in the WebService response. I am confused about how to use Let params{} The error message shows "object undefined". Addition ...

What is the best way to obtain and transmit an ID from an Angular dropdown menu selection

Can you assist me with a coding issue? In my template, I have a select dropdown with options saved in a list of settings. Each setting has its own unique id. I also have a data model in my interface for fields sent or received from the backend. How can I e ...

Is there a way to modify the antd TimePicker to display hours from 00 to 99 instead of the usual 00 to 23 range?

import React, { useState } from "react"; import "./index.css"; import { TimePicker } from "antd"; import type { Dayjs } from "dayjs"; const format = "HH:mm"; const Clock: React.FC = () =& ...