How to create Apollo client for multiple graphQL endpoints?
- Create HttpLink to each endpoint
import { ApolloLink } from "apollo-link";
const myLink = new HttpLink({
uri: '/graphql',
// other link options...
});
const thirdPartyLink = new HttpLink({
uri: 'website/graphql',
// other link options...
});
import { ApolloClient } from 'apollo-client';
const client = new ApolloClient({
link: ApolloLink.split(
operation => operation.getContext().clientName === "third-party",
// the string "third-party" can be anything you want,
// we will use it in a bit
thirdPartyLink, // <= apollo will send to this if clientName is "third-party"
myLink // <= otherwise will send to this
)
// other options
});
- Finally, you can call a query or mutation by passing the clientName to Apollo like this
useQuery(QUERY, { variables, context: { clientName: 'third-party' } })
// useQuery is a React hook, it may look different for you if you are using something else
Leave a Reply