在 Apollo Client 中使用多个端点

Using multiple endpoints in Apollo Client

这是我第一次在这里讨论 post。我通过奥德赛学习了Apollo + GraphQL。目前,我正在使用 Next.js 构建自己的项目,这需要从 2 GraphQL 端点.

获取数据

我的问题:如何使用 ApolloClient 多个 GraphQL 端点 获取数据?

下面是我的第一个端点的代码:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const client = new ApolloClient({
  ssrMode: true,
  link: createHttpLink({
    uri: "https://api.hashnode.com/",
    credentials: "same-origin",
    headers: {
      Authorization: process.env.HASHNODE_AUTH,
    },
  }),
  cache: new InMemoryCache(),
});

export default client;

您要完成的工作有点违背 Apollo 的“One Graph”方法。 查看网关和联合 - https://www.apollographql.com/docs/federation/

话虽如此,一些 hacky 解决方案是可能的,但您将需要维护更复杂的结构并在每个查询中指定端点,这会破坏内置机制并可能导致优化问题。

//Declare your endpoints
const endpoint1 = new HttpLink({
    uri: 'https://api.hashnode.com/graphql',
    ...
})
const endpoint2 = new HttpLink({
    uri: 'endpoint2/graphql',
    ...
})

//pass them to apollo-client config
const client = new ApolloClient({
    link: ApolloLink.split(
        operation => operation.getContext().clientName === 'endpoint2',
        endpoint2, //if above 
        endpoint1
    )
    ...
})

//pass client name in query/mutation
useQuery(QUERY, {variables, context: {clientName: 'endpoint2'}})

这个包似乎可以满足您的需求:https://github.com/habx/apollo-multi-endpoint-link

此外,请查看此处的讨论:https://github.com/apollographql/apollo-client/issues/84