Resolve two GraphQL schema fields using one endpoint

Resolve two GraphQL schema fields using one endpoint


2

There’s a situation where there are two possible types to fill data property. I have made a union type for that (ComponentItem) to determine which field needs to be returned. The first schema (ComponentItem1) should just be a hardcoded list but the second one (ComponentItem2) is more dynamic where it gets a searchTerm from query and it actually calls an endpoint to fill the list and also has hasNextPage property.

Here are the schemas I made:

type Component {
  id
  title
  data: ComponentItem
}
union ComponentItem = ComponentItem1 | ComponentItem2
type ComponentItem1 {
    list: [List!]!
}

type ComponentItem2 {
    hasNextPage: Boolean;
    list: [List!]!
}

In the resolver I’m resolving the union type in order to generate proper __typename:

const resolver: {
    ComponentItem: {
        __resolveType(object) {
            if(object.searchTerm){
               return "ComponentItem2"
            }
            return "ComponentItem1"
        },
    },
}

What I’m currently doing is to resolve the list and hasNextPage individually but in this scenario I’m sending the request to the same endpoint twice.

const resolver = {
   ...resolver,
   ComponentItem2: {
     list: async (root, __, context) => {
         const result = await fetch('search-endpoint')
         return result?.items || []
     }
     hasNextPage: async (root, __, context) => {
         const result = await fetch('search-endpoint')
         return result?.hasNextPage || false
     }

   }
   
}

My question is how it is possible to share that result in another field resolver (Other than using "context"). Or if there’s any better way to handle this situation let me know.

1

  • You can call the endpoint in the Component.data resolver. Can you share that code as well, please?

    – Bergi

    Jul 12, 2022 at 16:42

1 Answer
1


0

One option could be to lazy load that query in the context. Each resolver would call that property on the context, but only the first would actually execute it.



Leave a Reply

Your email address will not be published. Required fields are marked *