I have been using Apollo Server + Prisma. I was w...
# orm-help
i
I have been using Apollo Server + Prisma. I was wondering if there is a better way of doing the following. —— Gist: how can I cleanly
{include: true}
a relation in prisma only when that field is asked in GraphQL query? Say I have a Book table and an Author table. Book and Author are related. I have a GQL Query
Copy code
books {
  name
  author {
    name
  }
}
This resolves with
const books = await prisma.book.findMany({include: {author: true}})
. What if I did not ask for the author? Although Graphql wont send it to client, I would like to avoid that unnecessary join on orm level. I can use the info param of resolver function to see if that field was asked and conditionally use include in prisma but that is not scalable and kills the dx. I thought if resolver chains could help. But am not sure how to go about it. Any help is much appreciated. Thank you!
āœ… 1
j
A solution is to use a Resolver Chain to resolve the
author
separately from the book.
Copy code
const resolvers = {
  Query: {
    books() { return prisma.book.findMany() 
  }
  Book: {
    author(parent, args, context, info) {
      return prisma.authors.findOne({ id: parent.author_id})
    }
  }
}
šŸ’Æ 1
i
Thanks for the quick reply Jared! I will give resolver chains a go. :)
I have one doubt. If I resolve both of them separately, wouldn't there be a performance hit since we are avoiding nested reads? We will be doing two queries in place of one! Is that right?
j
You'll also probably see that Prisma will also actually run 2 queries anyway with an include. Query optimisation is slated for a later stage of the project from my understanding
🦜 1
i
Yes. I see two queries there. Thank you!
j
So to summarize, it all depends on your use-case and how your API is accessed. resolving both in the 1 prisma query will overall be faster if fetching all that data but that will not be efficient as your models and relations grow. using the dataloader pattern and resolver chain is more appropriate if you don't control the clients integrating with the API. there is a third option where you can parse the graphql tree to understand what they are querying for (I don't recommend this option as it's complex, especially with graphql field aliases)
i
Thank you so much!
n
Anbother option is to use @Ahmed’s
PrismaSelect
for this šŸ™Œ https://paljs.com/plugins/select/
i
This is it! Thank youu for going the extra mile. Developers make great communities!
j
Awesome! that's option 3 been done for you!
āœ”ļø 1