Apollo联邦如何实现2个服务返回不同的模型给同一个方法?
创始人
2024-09-09 12:02:46
0

假设我们有2个服务,Service A和Service B。它们都有一个名为getUser的方法,并且返回不同的用户模型。为了在Apollo联邦中使用它们,我们首先需要定义一个公共的User模型。

type User @key(fields: "id") {
  id: ID!
  name: String!
}

接下来,我们需要分别定义Service A和Service B的User模型,以及如何将它们映射到公共模型。

Service A的User模型:

type UserA {
  id: ID!
  name: String!
  age: Int!
}

extend type User @key(fields: "id") {
  id @external
  userA: UserA
    @requires(fields: "id")
}

Service B的User模型:

type UserB {
  id: ID!
  name: String!
  email: String!
}

extend type User @key(fields: "id") {
  id @external
  userB: UserB
    @requires(fields: "id")
}

在这里,我们使用了extends关键字来扩展公共User模型。然后,我们定义了与Service A或Service B的User模型对应的字段,例如userA和userB。我们还为这些字段定义了@requires指令,以指定需要哪些字段来解析它们。

一旦定义了User模型和它们的扩展,我们可以在服务的resolver中调用它们。

Service A的resolver:

{
  Query: {
    getUser(_, { id }, { dataSources }) {
      // Fetch UserA model from Service A's data source
      const userA = dataSources.serviceA.getUser(id);

      // Map UserA model to the common User model
      return {
        id: userA.id,
        name: userA.name,
        userA
      };
    }
  }
}

Service B的resolver:

{
  Query: {
    getUser(_, { id }, { dataSources }) {
      // Fetch UserB model from Service B's data source
      const userB = dataSources.serviceB.getUser(id);

      // Map UserB model to the common User model
      return {
        id: userB.id,
        name: userB.name,
        userB
      };
    }
  }
}

最后,我们需要在federation service中添加Service A和Service B。这将允许我们将它们合

相关内容

热门资讯

银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
Android|无法访问或保存... 这个问题可能是由于权限设置不正确导致的。您需要在应用程序清单文件中添加以下代码来请求适当的权限:此外...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
AsusVivobook无法开... 首先,我们可以尝试重置BIOS(Basic Input/Output System)来解决这个问题。...
ASM贪吃蛇游戏-解决错误的问... 要解决ASM贪吃蛇游戏中的错误问题,你可以按照以下步骤进行:首先,确定错误的具体表现和问题所在。在贪...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...