具有多个 GraphQL 端点的 Apollo

Posted

技术标签:

【中文标题】具有多个 GraphQL 端点的 Apollo【英文标题】:Apollo with multiple GraphQL endpoints 【发布时间】: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' 
  );

谢谢

【问题讨论】:

【参考方案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'
  );

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

【讨论】:

以上是关于具有多个 GraphQL 端点的 Apollo的主要内容,如果未能解决你的问题,请参考以下文章

Serverless graphql 拆分成微服务

Apollo 联合网关背后的 Hasura GraphQL 端点

将 2 个 REST 端点合并到单个 GraphQL 响应

我可以从 GraphQL 模式生成 REST 服务吗?

如何通过 REST API 在 Express Gateway 中使用多个路径和端点?

如何调试 Apollo GraphQL 服务器上的内存泄漏?