ApolloClient – How to use (1)

How to create Apollo client for multiple graphQL endpoints?

  • Create HttpLink to each endpoint
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 { ApolloLink } from "apollo-link"; const myLink = new HttpLink({ uri: '/graphql', // other link options... }); const thirdPartyLink = new HttpLink({ uri: 'website/graphql', // other link options... });
import { ApolloLink } from "apollo-link";

const myLink = new HttpLink({
  uri: '/graphql',
  // other link options...
});

const thirdPartyLink = new HttpLink({
  uri: 'website/graphql',
  // other link options...
});
  • Configure Apollo client
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
});
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 });
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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
useQuery(QUERY, { variables, context: { clientName: 'third-party' } })
// useQuery is a React hook, it may look different for you if you are using something else
useQuery(QUERY, { variables, context: { clientName: 'third-party' } }) // useQuery is a React hook, it may look different for you if you are using something else
useQuery(QUERY, { variables, context: { clientName: 'third-party' } })

// useQuery is a React hook, it may look different for you if you are using something else

Be the first to comment

Leave a Reply

Your email address will not be published.


*