Apollo Client Mux
apollo-client-mux
is a library designed to handle multiple GraphQL endpoints within a single Apollo Client instance. It allows you to set different caches and links for different endpoints.
Usage
Step 1: add @endpoint
directive to operation documents
import type { CodegenConfig } from "@graphql-codegen/cli";
import { addEndpointDirectiveForCodegen } from "apollo-client-mux/transform";
const config: CodegenConfig = {
generates: {
"src/gql/<yourEndpoint>/": {
preset: "client",
documentTransforms: [
{
transform: addEndpointDirectiveForCodegen({
endpointName: "yourEndpoint",
}),
},
],
},
},
};
export default config;
Step 2: Create ApolloCache and ApolloLink for multiple endpoints
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { ApolloCacheMux, withCacheMux } from "apollo-client-mux";
const InMemoryCacheMux = withCacheMux(InMemoryCache);
const yourEndpointCache = new InMemoryCache();
const cache = new InMemoryCacheMux({
mux:{
caches: {
yourEndpoint: yourEndpointCache,
},
}
});
const yourEndpointHttpLinnk = new HttpLink({ });
const defaultHttpLinnk = new HttpLink({ });
const link = createApolloLinkMux({
links: {
yourEndpoint: yourEndpointHttpLink,
},
defaultLink: defaultHttpLink;
});
const client = new ApolloClient({
cache,
link,
});