hi , I have a problem, I want to use a variable to...
# orm-help
z
hi , I have a problem, I want to use a variable to represent the name of the model, and I have models with the same fields, tried this
prisma[modelName].findMany()
, but I get this error:
This expression is not callable.
Each member of the union type has signatures, but none of those signatures are compatible with each other
(edited)
✅ 1
l
You might need to set the type of
modelName
to a union. If it's just a strong then ts might complain.
Copy code
type modelName = "model1" |"model2"
z
my code like this :
``` export async function getAllItemsOfOneClassifier({
classifier,
}: {
classifier: 'color' | 'biome';
}) {
const item = prisma[classifier];
const classifierItems = await item.findMany();
return classifierItems;
}```
@Lloyd Richards
This expression is not callable.
Each member of the union type '(<T extends ColorFindManyArgs>(args?: SelectSubset<T, ColorFindManyArgs> | undefined) => CheckSelect<T, PrismaPromise<Color[]>, PrismaPromise<...>>) | (<T extends BiomeFindManyArgs>(args?: SelectSubset<...> | undefined) => CheckSelect<...>)' has signatures, but none of those signatures are compatible with each other.
l
Do you get a TS error on the
item
? You might need to use the type that Prisma provides...
Copy code
classifier: prisma.color | prism.biome
Though, if it's only two cases then maybe just a switch would be enough for now:
Copy code
const items = switch(classifier){
  case "color":
    return prisma.color.findMany();
  case "biome":
    return prism.biome.findMany();
}
z
the error on
Copy code
findMany()
@Lloyd Richards
l
ah, i see the issue. Basically the
findMany()
is carefully typed to allow for the
where
,
include
etc options to work. But when its generic like this the function breaks down cause its scared you might pass an unknown variable into the props. The not so nice solution would be to just case item as any, since you know you're never going to pass any props in here. But if you did want to pass props then you could use a switch statement and use the classifer on primsa and typescript will be less angry:
Copy code
export async function getAllItemsOfOneClassifier({
  classifier,
}: {
  classifier:
    | { type: "color"; props: ColorProps }
    | { type: "biome"; props: BoimeProps };
}) {
  switch (classifier.type) {
    case "color":
      return await prisma[classifier.type].findMany(classifier.props);
    case "biome":
      return await prisma[classifier.type].findMany(classifier.props);
  }
}
Maybe someone at Prisma can give a more generic solution using some types from prisma client, but this seems the most sensible to me 🤷‍♂️
z
thanks for your help