将 Federation 中的 Rest 数据集与解析器合并?

Merging Rest datasets in Federation with resolvers?

GraphQL 和 Apollo Federation 的新手。

我有一个问题,是否可以用另一个数据集填充一个数据集,例如:

# in Shop Service
type carId {
 id: Int
}

type Shop @key(fields: "id") {
  id: ID!
  name: String
  carIds: [CarId]
}
# in Car Service
type Car {
  id: ID!
  name: String
}
extends type Shop @key(fields: "id") {
  id: ID! @external
  cars: [Car]
}

汽车解析器

Query{...},
Shop: {
    async cars(shop, _, { dataSources }) {
      console.log(shop); // Issue here is it returns the references that are an object only holding the `id` key of the shop, I need the `cars` key here, to pass to my CarsAPI
      return await dataSources.CarsAPI.getCarsByIds(shop.carsIds);
    }
  }

来自 Shop rest api 的响应如下所示:

[{id: 1, name: "Brians Shop", cars: [1, 2, 3]}, {id: 2, name: "Ada's shop", cars: [4,5,6]}]

从 Car rest api 响应看起来像:

[{id: 1, name: "Mustang"}, {id: 2, name: "Viper"}, {id: 3, name: "Boaty"}]

所以我要存档的是查询我的 GraphQL 服务器:

Shop(id: 1) {
  id
  name
  cars {
    name
 }
}

然后期望:

{
  id: 1,
  name: "Brian's shop",
  cars: [
    {name: "Mustang"},
    {name: "Viper"},
    {name: "Boaty"}
  ]
}

这可能吗,我选联邦的时候就是这么想的:)

因此,如果我在您发表评论后理解正确,您想要的是 cars 解析器内的 Shop 服务中的 carIds 进入您的 Car 服务。

您可以使用 @requires 指令,该指令将指示 Apollo Server 在开始执行 cars 解析器之前您需要一个(或几个)字段。即:

汽车服务

extend type Shop @key(fields: "id") {
  id: ID! @external
  carIds: [Int] @external
  cars: [Car] @requires(fields: "carIds")
}

现在,在 cars 解析器中,您应该可以通过第一个参数访问 shop.carIds

参见:https://www.apollographql.com/docs/apollo-server/federation/advanced-features/#computed-fields