Really like the solution by Pete for allowing more than just 2 endpoints.
decided to write my own version for better type checking.
Here is my take on his solution:
Typescript:
const defaultClient: keyof typeof clients = "heroku";
const clients = {
"heroku": new HttpLink({ uri: "https://endpointURLForHeroku" }),
"lists": new HttpLink({uri: "https://endpointURLForLists" })
}
const isRequestedClient = (clientName: string) => (op: Operation) =>
op.getContext().clientName === clientName;
const ClientResolverLink = Object.entries(clients)
.map(([clientName, Link]) => ([clientName, ApolloLink.from([Link])] as const))
.reduce(([_, PreviousLink], [clientName, NextLink]) => {
const ChainedLink = ApolloLink.split(
isRequestedClient(clientName),
NextLink,
PreviousLink
)
return [clientName, ChainedLink];
}, ["_default", clients[defaultClient]])[1]
declare module "@apollo/client" {
interface DefaultContext {
clientName: keyof typeof clients
}
}
JS:
const defaultClient = "heroku";
const clients = {
"heroku": new HttpLink({ uri: "https://endpointURLForHeroku" }),
"lists": new HttpLink({uri: "https://endpointURLForLists" })
}
const isRequestedClient = (clientName) => (op) =>
op.getContext().clientName === clientName;
const ClientResolverLink = Object.entries(clients)
.reduce(([_, PreviousLink], [clientName, NextLink]) => {
const ChainedLink = ApolloLink.split(
isRequestedClient(clientName),
NextLink,
PreviousLink
)
return [clientName, ChainedLink];
}, ["_default", clients[defaultClient]])[1]