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

Navigating between articles using React.js and Next.js

Imagine a scenario with two articles (for the complete example, visit https://github.com/codebushi/nextjs-starter-dimension/blob/master/components/Main.js) import PropTypes from 'prop-types'; class Main extends React.Component { render() { ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

Definition of TypeScript array properties

Having some trouble creating a type for an array with properties. Can't seem to figure out how to add typings to it, wondering if it's even possible. // Scale of font weights const fontWeights: FontWeights = [300, 400, 500]; // Font weight alia ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Next js is repeatedly calling a Firestore document in multiple instances during the fetching process

In my Next js 13 project, I am facing an issue while fetching a single document with an id from Firebase. Instead of returning just one read (which is expected since I'm fetching a single doc), it is returning multiple reads, sometimes ranging from 2 ...

Retrieving Information with NextJS and Material UI components in React

In my quest to develop dynamic pages displaying detailed information about individual books (such as title and author) on separate pages, I have encountered a hurdle. This challenge involves understanding how to call an API endpoint using NextJS to retriev ...

Module `coc-tsserver` not found (error ts2307)

Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the screenshot). I've already set ...

Creating a Blob or ArrayBuffer in Ionic 2 and Cordova: Step-by-Step Guide

Is there a way to generate a blob or an arrayBuffer with TypeScript when using the Camera.getPicture(options) method? I am currently working on an Ionic 2/Cordova project. var options = { quality: 90, destinationType: Camera.DestinationType.FILE_ ...

Netlify experiencing issues with redirecting URLs for specific rules

After implementing the redirects, I noticed that the first two are working correctly but the last one is not functioning as expected. It seems like there might be an issue with my approach. Redirects working: /forums https://test/forums 200 /forums/* ...

What is the process of declaring a method within a subclass and then retrieving it from a method within the parent class using Typescript?

I am currently working with this TypeScript code snippet: abstract class Base { static actions:Record<string,unknown> static getActions () { return this.actions } } class Sub extends Base { static actions = { bar:(bar:string ...

The dynamically rendered component cannot be assigned to the type 'IntrinsicAttributes & ContentOutlineProps & ContentBrainstormProps'

I am facing an issue on my page where a <SideBar /> component is causing a Typescript error with the setActivePage hook. The error message points to a specific line in my code: const Content: (({ question_blocks, }: ContentBrainstormProps) => JSX. ...

Issue: Angular 7 unable to route directly to URL with specific ID

When I click on the navigation link with code for button click, it works perfectly fine: this.router.navigate(['/dashboard', this.selectedDateString]); However, if I manually type the URL into the address bar like this: I receive a forbidden! ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

I'm having trouble getting Tailwind CSS colors to work with my Next.js components. Any tips on how to apply background colors

https://i.stack.imgur.com/8RGS3.png https://i.stack.imgur.com/FRTOn.png Hey there! I'm currently experimenting with using Tailwind background colors in my Next.js project. However, I'm facing an issue where the background color is not being appl ...

Is TypeScript declaration merging not functioning properly?

Trying to enhance an existing interface with a new member is causing Typescript errors for me. // foo.js export interface IOption { xOffset: number } import {IOption} from 'foo'; // Attempting to extend IOption with `yOffset`, but encounter ...

Is it necessary to use a Node server to run a dynamic website if I am not utilizing server-side rendering (SSR)?

Is it necessary to use a node server for dynamic websites in Next.js if server-side rendering is not used? Unlike React, Next.js does not generate an index.html file on its own. This means that the project cannot be run without a node server. I hope I ha ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Encountering an error with Angular2 when referencing node modules

I encountered an issue when trying to use angular2 from the node_modules directory. Can anyone guide me on how to resolve this error? Is there something specific I need to include in my HTML file? I am looking for a Git repository where I can access Angu ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...

What is the best way to outline this model using typescript?

Here is a JSON model that I am working with: { "loggers" : { "logger1" : { "name" : "logger1", "level" : "DEBUG", "sub_loggers" :{ "logger1.nested_logger1" : { "name": "lo ...