合并联盟中的Rest数据集与解析器?

时间:2019-09-19 16:42:24

标签: graphql apollo apollo-server apollo-federation

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

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

1 个答案:

答案 0 :(得分:1)

因此,如果在您发表评论后我能正确理解,您想要的是让carIds分解器中的cars商店服务进入您的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