Explicitly specifying an object in Prisma with its foreign relationships

I've set up my schema as an approximation of a directory structure: directories (ADirs) and documents (ADocs). Directories and documents can have a parent directory, which is a foreign key. I can write queries to retrieve directories and their children (childDirs, childDocs) without issue, but if I specify a directory as a state variable in a client component with useState, the type definition for ADir that I get from importing @prisma/clientdoes not have the children as a property. I've circumvented this issue by extending the type with my own interface, but I feel like it's a messy fix. Any tips? Thanks.
// helper for ADir object types that also need their children
// TODO: is there a better way to specify foreign objects in a type?
export interface ADirWithChilren extends ADir {
childDirs: ADir[],
childDocs: ADoc[]
}
// helper for ADir object types that also need their children
// TODO: is there a better way to specify foreign objects in a type?
export interface ADirWithChilren extends ADir {
childDirs: ADir[],
childDocs: ADoc[]
}
further reference: related libs are just next (using app router) and prisma. No trpc, zod, or superjson packages, but not against them if they are key to a good implementation.
Solution:
so then I'd get a type like this
export type Dir = Awaited<ReturnType<typeof getDir>>[number];
export type Dir = Awaited<ReturnType<typeof getDir>>[number];
...
Jump to solution
5 Replies
bakdaddy
bakdaddy2y ago
I think it's because under the hood Prisma only makes the relations on its own level, so it's a little messy. I had a similar issue, what I did was I extracted the type from the query itself. Say you have a query
const getDir = async () => {
const dir = await prisma.adir.findMany({
include: {
childDirs: true,
childDocs: true
}
})
return dir
}
const getDir = async () => {
const dir = await prisma.adir.findMany({
include: {
childDirs: true,
childDocs: true
}
})
return dir
}
Solution
bakdaddy
bakdaddy2y ago
so then I'd get a type like this
export type Dir = Awaited<ReturnType<typeof getDir>>[number];
export type Dir = Awaited<ReturnType<typeof getDir>>[number];
bakdaddy
bakdaddy2y ago
it would get back the typings exactly as the return type of getDir()
[number]
[number]
it's for a singular item, as getDir returns an array of items
dumbitry
dumbitryOP2y ago
thanks for your help! It's working out well.
bakdaddy
bakdaddy2y ago
No problems, happy to help
Want results from more Discord servers?
Add your server