Apollo联邦如何实现2个服务返回不同的模型给同一个方法?
创始人
2024-09-09 12:01:15
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。这将允许我们将它们合

相关内容

热门资讯

线上(wepoke真的)原来是... 线上(wepoke真的)原来是真的有挂!其实真的有挂(2022已更新)(哔哩哔哩);亲,其实确实真的...
两教程(Wepoke程序)软件... 两教程(Wepoke程序)软件透明挂辅助工具(软件透明挂)透视辅助(2024已更新)(哔哩哔哩);致...
软件(wepoke透明)原来是... 软件(wepoke透明)原来是真的有挂!其实真的有挂(2020已更新)(哔哩哔哩)是一款可以让一直输...
一模拟器(德扑工具)外挂辅助工... 一模拟器(德扑工具)外挂辅助工具(透视)透视辅助(2025已更新)(哔哩哔哩);亲真的是有正版授权,...
系统(aapoker讲解)竟然... 系统(aapoker讲解)竟然真的有挂!其实真的有挂(2021已更新)(哔哩哔哩);aapoker讲...
6系统(aapoker下载)外... 6系统(aapoker下载)外挂辅助工具(辅助挂)透视辅助(2023已更新)(哔哩哔哩)aapoke...
智能(德扑之星刷数据)果真真的... 智能(德扑之星刷数据)果真真的有挂!原来真的有挂(2025已更新)(哔哩哔哩);《WPK辅助透视》‌...
1机器人(德州nzt软件)软件... 1机器人(德州nzt软件)软件透明挂辅助软件(透视)透视辅助(2022已更新)(哔哩哔哩);人气非常...
ai代打(德扑之星决策)确实是... ai代打(德扑之星决策)确实是真的有挂!原来真的有挂(2020已更新)(哔哩哔哩);科技详细教程小薇...
第8透明(wepoke数据)外... 第8透明(wepoke数据)外挂透明挂辅助神器(辅助挂)透视辅助(2023已更新)(哔哩哔哩);原来...