Search code examples
graphqlapolloreact-apollo

Apollo - How to pass a Union type to ApolloClient


I'm using the Shopify GraphQL to apply a mutation as shown at the bottom.

I want to declare a union type for ShopifyReturnUrl in that mutation for which I have declared this:

import gql from 'graphql-tag';

const shopifyReturnUrl = gql`
  union ShopifyReturnUrl = String | URL
`;

However how do I actually get this into my ApolloClient instance which is currently defined like so:

const client = new ApolloClient({
    fetchOptions: {
        credentials: 'include'
    },
});

And for context, I'm using this in my React app like so:

<ApolloProvider client={client}>
    <Component {...pageProps} />
</ApolloProvider>

Finally, the mutation where I actually want to use ShopifyReturnUrl

export const SUBSCRIPTION_MODIFY = gql`
  mutation($subName: String!, $subPrice: String!, $returnUrl: ShopifyReturnUrl) {
    appSubscriptionCreate(
        name: $subName
        returnUrl: $returnUrl
      ) 
  }
`

Any help appreciated.

Thanks.


Solution

  • There's a couple of issues here:

    • Unions can only be created for object types, not scalars like String.
    • Type definitions are written on the server, not on the client. As a client, you can't add additional types to the schema that's exposed by the server since the server wouldn't know how to handle those types.
    • If appSubscriptionCreate takes a returnUrl argument, then the variable you pass to that argument (in this case named $returnUrl) should be of the same type as the argument. If you don't know the type of the argument, check your server's documentation or its GraphiQL interface (if it exposes one). In this specific case, the argument's type is URL!, so that's what your variable should be.