7

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?

Siamak Motlagh
  • 5,028
  • 7
  • 41
  • 65

1 Answers1

-1

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: {},
})
  • 3
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 15 '21 at 17:09
  • 1
    This is what I already mentioned in my question. My question: `Is there any better way rather than doing it nested?` – Siamak Motlagh Sep 16 '21 at 06:54