【问题标题】:Apollo with multiple GraphQL endpoints具有多个 GraphQL 端点的 Apollo
【发布时间】:2021-11-14 14:34:25
【问题描述】:

我需要使用多个 GraphQL 架构,我目前已经安装了


expo:sdk 42“@apollo/client”:“^3.4.11”,“apollo-link”:“^1.2.14”,“graphql”:“^15.5.3”,强>

只要我使用单一模式,一切正常:声明单一模式

App.js

import { ApolloProvider, ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { ApolloLink } from 'apollo-link';

const httpLink = createHttpLink({
    uri: `${serverBaseUrl}/client/graphql`,
  });


const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        /**@all headers*/
      }
    }
  });

const client = new ApolloClient({
   link: authLink.concat(httpLink),
   cache: new InMemoryCache(),
   credentials: 'include'
});

<ApolloProvider client={client}>
 /**@all*/

查询 Example.jsx

import { gql, useQuery } from "@apollo/client";

  const E_QUERY = gql`
  query{
      example(sortBy: { field: "updatedAt", order: DESC }){
        _id
      }
  }
`;

const { loading, data } = useQuery(E_QUERY , {    
    fetchPolicy: "network-only",
  });

现在一切顺利

但是当我添加多个模式时它不会产生任何错误,它只是保持单独加载


App.js

const client = new ApolloClient({
    link: ApolloLink.split(
      operation => operation.getContext().clientName === "adminGQL",
      authLink.concat(httpLinkAdmin), 
      operation => operation.getContext().clientName === "agentGQL",
      authLink.concat(httpLinkAgent), 
      operation => operation.getContext().clientName === "client",
      authLink.concat(httpLinkAgent), 
    ),
    cache: new InMemoryCache(),
    credentials: 'include'
  });

Example.jsx

const { loading, data } = useQuery(EXAMPLE_QUERY , {    
    fetchPolicy: "network-only",
    context: { clientName: 'client' }
  });

谢谢

【问题讨论】:

    标签: reactjs react-native graphql expo apollo


    【解决方案1】:

    检测到的第一个错误是 ApolloLink.split 只能进行比较,它只有两种可能的情况(真或假)所以不能添加两个以上的 url,那么如何添加超过 2 个 url ?

    ApolloLink.d.ts

    static split(test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler): ApolloLink;
    

    从这一点开始我们有如下解决方案

    const client = new ApolloClient({
        link: ApolloLink.split(
          operation => operation.getContext().clientName === "adminGQL",
          authLink.concat(httpLinkAdmin), 
          authLink.concat(ApolloLink.split(
            operation => operation.getContext().clientName === "agentGQL",
            httpLinkAgent, 
            httpLink
          ))
        ),
        cache: new InMemoryCache(),
        credentials: 'include'
      });
    

    这可能不是最好的解决方案,但它是我能够构建的。所以新的建议或解决方案可能会受到欢迎。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2020-10-18
      • 2019-01-09
      • 1970-01-01
      • 2020-10-06
      • 2020-06-29
      • 2020-02-06
      • 2020-10-07
      相关资源
      最近更新 更多