2

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"}
  ]
}

这可能吗,这是我选择联邦时的想法:)

4

1 回答 1

2

因此,如果我在您的评论后理解正确,那么您想要的是在解析器carIds中的 Car 服务中提供 from Shop 服务。cars

您可以使用该指令指示 Apollo Server 在开始执行解析器@requires之前需要一个(或几个)字段。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

于 2019-09-20T12:30:15.090 回答