I’m trying to use a more generic method to get data from prisma, and my function currently looks like this:
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);
}
}
However when calling findMany()
on the resource it give me an error:
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’m not sure why this is not ok, since everything that would be in Prisma.ModelName
should have the findMany
method. Is there a better type I missed or is there something fundamentally wrong with how I’m doing this?
I’ve tried a few things at this point, but I think this is more likely me not understanding how this works.