Multiple ApolloLink based on context

Viewed 2091

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?

1 Answers

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: {},
})
Related