Multiple ApolloLink based on context

4.2k Views Asked by At

I want to implement a way to switch over different links based on the context set in graphql query. What I did so far is something like this which is working fine but doesn't seem to be a nice solution over time.

const link = ApolloLink.from([
  HandlerLink1,
  HandlerLink2,
  ApolloLink.split(
    operation => operation.getContext().service === "x",
    LinkX,
    ApolloLink.split(
      operation => operation.getContext().service === "y",
      LinkY,
      ApolloLink.split(
        operation => operation.getContext().service === "z",
        LinkZ,
        LinkN
      )
    )
  )
]);

Is there any better way rather than doing it nested?

2

There are 2 best solutions below

1
On

Solution resolve

    export const client = (): ApolloClient<any> =>
  new ApolloClient({
    link: ApolloLink.split(
      (operation) => operation.getContext().clientName === 'core',
      urlCore,

      ApolloLink.split(
        (operation) => operation.getContext().clientName === 'user',
        urlUsers,
        urlPrueba1,
      ),

      ApolloLink.split(
        (operation) => operation.getContext().clientName === 'prueba1',
        urlPrueba1,
        urlPrueba2,
      ),

      ApolloLink.split(
        (operation) => operation.getContext().clientName === 'prueba2',
        urlPrueba2,
        urlPrueba3,
      ),
    ),
    // headers: addHeaders({}),
    cache: new InMemoryCache(),
  });
2
On

I have also encountered the same problem. The below code works fine for me

const client = new ApolloClient({
  cache,
  link: ApolloLink.split(
    (operation) => operation.getContext().clientName === 'link1',
    Link1, // <= apollo will send to this if clientName is "link1"

    ApolloLink.split(
      (operation) => operation.getContext().clientName === 'link2',
      Link2,// <= apollo will send to this if clientName is "link2"
      Link3,// <= else Link3 will run
    ),
  )
  resolvers: {},
})