跳至内容

多个客户端

如果您的应用程序需要连接到不同的 GraphQL 端点,您可以指定多个 apollo 客户端

js
const defaultOptions = {
  // You can use `wss` for secure connection (recommended in production)
  // Use `null` to disable subscriptions
  wsEndpoint: process.env.VUE_APP_GRAPHQL_WS || 'ws://localhost:4000/graphql',
  // LocalStorage token
  tokenName: AUTH_TOKEN,
  // Enable Automatic Query persisting with Apollo Engine
  persisting: false,
  // Use websockets for everything (no HTTP)
  // You need to pass a `wsEndpoint` for this to work
  websocketsOnly: false,
  // Is being rendered on the server?
  ssr: false,
}

const clientAOptions = {
    // You can use `https` for secure connection (recommended in production)
    httpEndpoint: 'http://localhost:4000/graphql',
}

const clientBOptions = {
  httpEndpoint: 'http://example.org/graphql',
}

// Call this in the Vue app file
export function createProvider (options = {}) {
  const createA= createApolloClient({
    ...defaultOptions,
    ...clientAOptions,
  });

  const createB = createApolloClient({
    ...defaultOptions,
    ...clientBOptions,
  });

  const a = createA.apolloClient;
  const b = createB.apolloClient;

  // Create vue apollo provider
  const apolloProvider = createApolloProvider({
    clients: {
      a,
      b
    }
    defaultClient: a,
})

在组件的 apollo 选项中,您可以使用 $client 为所有查询、订阅和变异定义客户端(仅限于此组件)

js
export default {
  apollo: {
    $client: 'b',
  },
}

您也可以在选项中使用 client 属性在单个查询、订阅和变异中指定客户端

js
tags: {
  query: gql`...`,
  client: 'b',
}