P
Prisma8mo ago
Bean

union type findMany

I want to be able to query in prisma using a variable which is a union type over mulitple model tables. so instead of
const model : 'user' | 'post' | ...;
const id : number = 1;

switch (model) {
case 'user': prisma.user.findMany({where : id})
case 'post': prisma.post.findMany({where : id})
}
const model : 'user' | 'post' | ...;
const id : number = 1;

switch (model) {
case 'user': prisma.user.findMany({where : id})
case 'post': prisma.post.findMany({where : id})
}
I want to be able to do:
const model : 'user' | 'post' | ...
prisma[model].findMany({where : id} as const)
const model : 'user' | 'post' | ...
prisma[model].findMany({where : id} as const)
Since I have a really large schema and I do not want to repeat so many lines. but, even though each model/schema table has the id field as the same type and they all have this same key, TS is complaining that the signatures of each of the findMany functions are different for each table so I cannot do this. . I even tried using as const in case there was a difference there, but that did not help either. I am not sure how I can do this to make my code cleaner and easier to maintain. Here is an example in a codesandbox: https://codesandbox.io/p/devbox/dark-night-vsqs73
9 Replies
snchmt
snchmt8mo ago
Could you create a TS playground with the code ?
Bean
BeanOP8mo ago
@snchmt did you figure it out?
snchmt
snchmt8mo ago
Sorry, I was waiting for your modifications I forgot to check again I think the issue here is that you are using a generic method that uses the generic type of an interface, but the generic types of the interfaces are not compatible, so the only way possible here is to cast somewhere or use a ts-ignore
Bean
BeanOP8mo ago
I know. but then I would completely lose TS errors which I really do not want. I wish there was a way for prisma to allow this directly in their TS code gen.
David
David8mo ago
Bean
BeanOP8mo ago
i dont get the point of this. this doesnt solve my problem at all
David
David8mo ago
What are you ultimately trying to achieve? My assumption was that you want to create an abstraction over something you do often without knowing which model beforehand
Bean
BeanOP8mo ago
I want to be able to make a defined operation that is long (find many where [x or y], select foo, include bar), over many different tables. but I want want to copy paste the code in case I need to change the query. so I want to be able to pass the table name as a variable and be type safe. ya know. like what my original post said.....
David
David8mo ago
So what is the issue with passing prisma.modelName instead of "modelName"? You're making it very hard for yourself in terms of TS by wanting a string, especially since it has the same result. No need for an attitude towards someone that is trying to help you, my guy
Want results from more Discord servers?
Add your server