Apollo Client Mux

raw JSON →
0.0.3 verified Wed Apr 22 auth: no javascript

apollo-client-mux is an early-stage library, currently at version 0.0.3, designed for advanced GraphQL client configurations. It enables a single Apollo Client instance to manage interactions with multiple distinct GraphQL endpoints. The library achieves this by allowing developers to define separate ApolloCache and ApolloLink instances for each endpoint, which are then integrated into a 'muxed' cache and link. This approach is particularly useful in microservice architectures or when integrating with multiple third-party GraphQL APIs, where different data models and network configurations necessitate isolated caching and request routing. It integrates with `@graphql-codegen` via a transformation utility to automatically apply an `@endpoint` directive to operation documents, ensuring queries and mutations are routed to the correct endpoint. Its current low version suggests active development and potential for API changes.

error TypeError: (0 , _apollo_client_mux_transform__WEBPACK_IMPORTED_MODULE_2__.addEndpointDirectiveForCodegen) is not a function
cause Incorrect import path or CommonJS `require()` syntax used in an ESM context for `addEndpointDirectiveForCodegen`.
fix
Ensure you are using import { addEndpointDirectiveForCodegen } from 'apollo-client-mux/transform'; and that your module resolution is configured for ESM.
error Error: Apollo Client Mux: Endpoint 'yourEndpointName' not found in muxed links/caches.
cause The endpoint name specified in an operation's `@endpoint` directive (or implicitly via codegen) does not have a corresponding entry in the `links` or `caches` object passed to `createApolloLinkMux` or `withCacheMux`.
fix
Double-check that the endpointName option in addEndpointDirectiveForCodegen matches the keys provided in the links and caches configuration for the multiplexers.
error Invariant Violation: 'cache' must be an instance of ApolloCache or a function that returns one.
cause Often occurs if `withCacheMux` is not correctly used to instantiate the cache, or if an incorrect `ApolloCache` instance is passed to the `ApolloClient`.
fix
Ensure withCacheMux(InMemoryCache) is called and then new InMemoryCacheMux(...) is used to create the actual cache instance. Verify that the resulting object is what's passed to ApolloClient's cache option.
breaking As a very early-stage library (v0.0.3), the API surface is highly subject to breaking changes. Developers should expect frequent updates and potential refactors in minor and patch versions.
fix Monitor GitHub repository for release notes and changelogs. Pin specific patch versions or implement robust integration tests.
gotcha Endpoint names used in `addEndpointDirectiveForCodegen` (via `endpointName` option) must exactly match the keys in the `mux.caches` and `mux.links` objects when initializing `InMemoryCacheMux` and `createApolloLinkMux`.
fix Ensure consistent string literals for endpoint names across your `graphql-codegen` configuration and Apollo Client setup. Use TypeScript enums or constants to avoid typos.
gotcha This library critically depends on `@graphql-codegen` for applying the `@endpoint` directive. Without proper codegen setup, the multiplexing functionality will not route operations correctly, defaulting all to the `defaultLink` and `defaultCache`.
fix Follow the documentation for `graphql-codegen` and the library's `addEndpointDirectiveForCodegen` utility. Verify that the generated operation documents include the `@endpoint` directive correctly for your target endpoints.
npm install apollo-client-mux
yarn add apollo-client-mux
pnpm add apollo-client-mux

Demonstrates configuring graphql-codegen to add an `@endpoint` directive and then setting up an Apollo Client instance with a multiplexed cache and link for multiple GraphQL endpoints.

import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import { ApolloCacheMux, withCacheMux, createApolloLinkMux } from 'apollo-client-mux';
import type { CodegenConfig } from '@graphql-codegen/cli';
import { addEndpointDirectiveForCodegen } from 'apollo-client-mux/transform';

// --- GraphQL Codegen Configuration (for your endpoint) ---
// This config snippet assumes you have graphql-codegen setup
// and want to route operations for 'yourEndpoint' through the mux.
const codegenConfig: CodegenConfig = {
  schema: 'http://localhost:4000/graphql', // Your endpoint's schema
  generates: {
    'src/gql/yourEndpoint/': {
      preset: 'client',
      documentTransforms: [
        {
          transform: addEndpointDirectiveForCodegen({
            endpointName: 'yourEndpoint' // Must match the name used in client setup
          })
        }
      ]
    }
  }
};

// --- Apollo Client Mux Setup ---

// 1. Create muxed cache
const InMemoryCacheMux = withCacheMux(InMemoryCache);
const yourEndpointCache = new InMemoryCache();
const defaultCache = new InMemoryCache();

const cache = new InMemoryCacheMux({
  mux: {
    caches: {
      yourEndpoint: yourEndpointCache // Cache specifically for 'yourEndpoint'
    }
  },
  // Options for the default cache (used when no @endpoint directive is present)
  ...defaultCache.extract()
});

// 2. Create muxed link
const yourEndpointHttpLink = new HttpLink({ uri: 'http://localhost:4001/graphql' });
const defaultHttpLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });

const link = createApolloLinkMux({
  links: {
    yourEndpoint: yourEndpointHttpLink // Link specifically for 'yourEndpoint'
  },
  defaultLink: defaultHttpLink // Link for operations without @endpoint
});

// 3. Create Apollo Client instance with muxed cache and link
const client = new ApolloClient({
  cache,
  link
});

console.log('Apollo Client with Muxed Endpoints initialized:', client);

// Example: Execute a query (assuming your codegen generated this)
// client.query({ query: YourEndpointQueryDocument });