Can someone help me troubleshoot why findMany is not functioning properly within my generic Prisma service? Additionally, what steps can I take

I'm currently tackling a project that involves creating a versatile service to display all entries from any Prisma model within my application. My approach utilizes TypeScript in conjunction with Prisma, aiming to dynamically pass a Prisma model to the service function and retrieve the results of the findMany query.

Below is the code snippet I've developed thus far:

import { PrismaClient } from '@prisma/client'

type PrismaClientMethod = '$on' | '$connect' | '$disconnect' | '$use' | '$executeRaw' | '$executeRawUnsafe' | '$queryRaw' | '$queryRawUnsafe' | '$transaction'
type PrismaModelName = keyof Omit<PrismaClient, PrismaClientMethod>
type PrismaModel = PrismaClient[PrismaModelName]

export const genericPrismaListService = async <T extends PrismaModel>(model: T) => {
  return model.findMany()
}

However, upon attempting to utilize the genericPrismaListService, I encountered issues where the findMany method was not being recognized. TypeScript errors pointed out that findMany did not exist on the type T. Despite passing a Prisma model, it seems that the accessibility of the findMany method is not as straightforward as anticipated.

Could the problem stem from incorrectly typing the model within the generic function, or might there be another underlying issue regarding how Prisma models are used generically in TypeScript? How can I ensure that methods like findMany, create, update, and others are readily available for the model being passed?

I would greatly appreciate any guidance on properly structuring the types in this function and making findMany operational. Thank you for your assistance!

Answer №1

import { PrismaClient, Prisma } from '@prisma/client'

// Creating a generic Prisma list service
type ModelName = keyof PrismaClient
type ModelType = PrismaClient[ModelName]

export const createGenericListService = async <T extends ModelType>(modelName: ModelName) => {
    const prisma = new PrismaClient()
    // Dynamically access the model
    const model = prisma[modelName] as T
    // Call findMany on the model
    return model.findMany()
}

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 session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Struggling with transitioning from TypeScript to React when implementing react-data-grid 7.0.0

I'm trying to add drag and drop functionality to my React project using react-data-grid, but I keep encountering a "TypeError: Object(...) is not a function" error. I have a TypeScript version of the file in the sandbox as a reference, but when I try ...

What is the best way to inject the Service into the Controller constructor using TypeScript?

I am developing a straightforward REST API using TypeScript that interacts with your classes to query a database in the following sequence: Controller > Service > Repository. While working on this, I experimented with the following code snippets: Co ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Creating a Type that limits its keys to those from another Type, with the ability to assign new values to those keys. Attempting to introduce new keys should result in an

type Numbers = { a: number; b: number; f: number; }; type ValidateKeysWithDifferentTypes = SomeThingKeyOf<Numbers> & { a: string; b: Date; c: null; // Error occurs because 'c' is not found in Numbers type? // Error due ...

Steps to assign a JSON file to an array within an object in Angular

What is the best way to assign a JSON file to an array within my "Client" object? I currently have a JSON file named Clients.json with the following structure: { "clients": [ { "firstName": "nameA", "lastName": "lastA", "doctorsNam ...

Implementing Expand/Collapse functionality for multiple TableRow components in Material-UI

Using a Material UI table and attempting to expand the `TableRow` inside a collapse table, but encountering an issue. Currently, all collapses are connected to one state for "open," causing all lists to open if one is clicked. What is the optimal approach ...

Uncertainty surrounding refinement in Typescript

I've been diving into the book Programming TypeScript, and I'm currently stuck on understanding the concept of refinement as shown in this example: type UserTextEvent = { value: string; target: HTMLInputElement }; type UserMouseEvent = { value: [ ...

Having issues with sitemap.xml functionality in Next.js post build

I've encountered an issue while working on my Next.js project. Everything runs smoothly in development, but once I build the project for production, the /sitemap.xml URL doesn't return any data. To address this problem, I created a sitemap.ts fi ...

Solve the error "Property 'container' of null is not accessible" in musickit.js while running an Angular application on a server

I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...

Octokit: Unable to create multiple Labels at once

Issue with Creating Multiple Labels Example Code: Promise.all( srcRepoReq.data.map(async (label) => { const newLabel: ghLabel = { name: label.name, color: label.color, description: label.description, ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

Implementing strict validation for Angular @Input by allowing only predefined values

I am facing an issue where I receive a string value as a parameter in a component, but I want to restrict the possible values that can be passed as a parameter, similar to using an enum. Currently, I have: @Input() type: string = ''; However, ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

Mastering the art of utilizing GSI Index and FilterExpression in AWS DynamoDB querying

In my DynamoDB database table, I have the following structure. It consists of a primary key (ID) and a sort key (receivedTime). ID(primary key) receivedTime(sort key) Data ID1 1670739188 3 ID2 167072 ...

Leveraging mobile interactivity in Angular2

Seeking assistance with implementing swipe events on mobile devices for Angular 2. I came across a mention of using Hammer.js for mobile event handling in this Github issue. Encountering an error when trying to bind the swipe event: EXCEPTION: Hammer.j ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

Troubleshooting Problems with Tsconfig and Output Directory

I'm experiencing an issue with the outDir setting in my tsconfig.json file. Here is what my tsconfig file looks like: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, ...

Encountering an error with the Angular 2 SimpleChanges Object during the initial npm start process

Within my Angular 2 application, there exists a component that holds an array of objects and passes the selected object to its immediate child component for displaying more detailed data. Utilizing the "SimpleChanges" functionality in the child component a ...