0

I'd like to know if there is a way to join two rest API on the name attribute using graphql. 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

// 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?

user3849960
  • 120
  • 2
  • 11

1 Answers1

0

GraphQL does not have support to join 2(or more) API's in some attributes. What you could do, is to fetch the data from both API's in the resolver and create an object with both results.

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.

Marco Daniel
  • 5,467
  • 5
  • 28
  • 36