简体   繁体   English

graphql:其余API连接

[英]graphql: rest API join

I'd like to know if there is a way to join two rest API on the name attribute using graphql . 我想知道是否有一种方法可以使用graphqlname属性上连接两个rest API。 These are the response that I have 这些是我的回应

// products API
[
 {
  id: "0001",
  name: "a name",
  color: "black",
  size: "L"
 },
 {
  id: "0002",
  name: "an other name",
  color: "red",
  size: "M"
 }
]

// price API
[
 {
  id: "xyz1",
  name: "a name",
  price: 10
 },
 {
  id: "xyz2",
  name: "an other name",
  price: 20
 }
]

and I want to use graphql to combine them, so that 我想使用graphql来组合它们,以便

// response from graphql
[
 {
  id: "0001",
  name: "a name",
  price: 10,
  color: "black",
  size: "L"
 },
 {
  id: "0002",
  name: "an other name",
  price: 20,
  color: "red",
  size: "M"
 }
]

Is graphql the right tool? graphql是正确的工具吗?

GraphQL does not have support to join 2(or more) API's in some attributes. GraphQL不支持在某些属性中加入2(或更多)API。 What you could do, is to fetch the data from both API's in the resolver and create an object with both results. 您可以做的是从解析器中的两个API获取数据,并创建一个同时具有两个结果的对象。

Something like (pseudo-code): 类似于(伪代码)的东西:

const products: yourDefinedType = []

fetch.productsAPI(productFromAPI
   fetch.pricesAPI(pricesFromAPI
      if (pricesFromAPI.name === productFromAPI.name) {
         product.push({
           id: productFromAPI.id,
           name: productFromAPI.name,
           color: productFromAPI.color,
           size: productFromAPI.size,
           price: pricesFromAPI.price
         })
      }
   )      
)

Keep in mind that this would have performance issues as you'd make a fetch to all prices per each product. 请记住,这会带来性能问题,因为您会获取每种产品的所有价格。 Another way would be to make your prices REST api to support get a price by name and fetch only the prices you need. 另一种方法是使您的价格REST api支持按名称获取价格并仅获取您需要的价格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM