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!