I’m currently working on a project where I’m trying to implement a generic service to list all entries from any Prisma model in my application. I’m using TypeScript with Prisma, and the idea is to pass a Prisma model dynamically to this service function and have it return the result of the findMany query.
Here’s the code I have so 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, when I try to use this genericPrismaListService, I run into issues where the findMany method doesn’t seem to be recognized. I get TypeScript errors suggesting that findMany does not exist on the type T. My understanding is that since I’m passing a model from Prisma, the findMany method should be available on any Prisma model, but that doesn’t seem to be the case here.
Am I incorrectly typing the model in the generic function, or is there another issue with how I’m using Prisma models generically in TypeScript? What can I do to ensure that findMany (and other model-specific methods like create, update, etc.) are available on the passed model?
Any help on how I can properly type this function and make findMany work would be greatly appreciated. Thank you in advance!
import { PrismaClient, Prisma } from '@prisma/client'
// Define the type for model names
type PrismaModelName = keyof PrismaClient
// Define the type for the model methods
type PrismaModel = PrismaClient[PrismaModelName]
export const genericPrismaListService = async <T extends PrismaModel>(modelName: PrismaModelName) => {
const prisma = new PrismaClient()
// Access the model dynamically
const model = prisma[modelName] as T
// Call findMany on the model
return model.findMany()
}
1