Graphql 将联合中的Rest数据集与解析程序合并?

Graphql 将联合中的Rest数据集与解析程序合并?,graphql,apollo,apollo-server,apollo-federation,Graphql,Apollo,Apollo Server,Apollo Federation,对GraphQL和阿波罗联盟来说是个新鲜事 我有一个问题,是否可以用一个数据集填充另一个数据集,例如: # in Shop Service type carId { id: Int } type Shop @key(fields: "id") { id: ID! name: String carIds: [CarId] } 汽车分解器 Query{...}, Shop: { async cars(shop, _, { dataSources }) { con

对GraphQL和阿波罗联盟来说是个新鲜事

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

# in Shop Service
type carId {
 id: Int
}

type Shop @key(fields: "id") {
  id: ID!
  name: String
  carIds: [CarId]
}
汽车分解器

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]}]
[{id: 1, name: "Mustang"}, {id: 2, name: "Viper"}, {id: 3, name: "Boaty"}]
从Car rest api中,响应如下所示:

[{id: 1, name: "Brians Shop", cars: [1, 2, 3]}, {id: 2, name: "Ada's shop", cars: [4,5,6]}]
[{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"}
  ]
}

这是否可能,这是我在选择federation时的想法:)

因此,如果我在您的评论后理解正确,您想要的是将
cars
解析程序中的
carid
从您的汽车服务中引入

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

汽车服务

extend type Shop @key(fields: "id") {
  id: ID! @external
  carIds: [Int] @external
  cars: [Car] @requires(fields: "carIds")
}
现在,在
cars
resolver中,您应该能够在第一个参数上访问
shop.carIds


请参阅:

您的问题有点让人困惑。1) 什么是扩展类型的“服务”?2) 你说你需要在解析器中输入“cars”键,而解析器返回的值实际上定义了它?@edmundo,1。类型错误应该是“扩展类型车间”,现在已更正。2.我想把“carIds”变成真正的汽车。在shop service中,我可以访问来自rest响应的ID,然后我想通过扩展来自汽车服务的数据来扩展该商店,因此我在汽车服务中解析shop.cars,因为我可以根据shop.carid获取汽车,我的问题是,我不知道如何将Shop.carIds传递给汽车服务。也为解析程序中的混乱感到抱歉,它应该说getCarsById(Shop.carIds),现在已修复。谢谢,这完全救了我一天!谢谢你在计算键上找到文档,我找不到!