I am using GraphQl together with bigcommerce to grab products, and i need to find a sollution to make my query dynamic - its based on the length of an array of SKU's. Its no problem to make it work with one product.
let query = `
query getProductBySku($sku: String) {
site {
product(sku: $sku) {
id
entityId
name
sku
}
}
}
`
And i figured out so far that i need to use something like aliases in graphql to be able to get several products in several response like this
query productById {
site {
o1: product(entityId: 167) {
id
entityId
sku
name
}
o2: product(entityId: 168 ) {
id
entityId
sku
name
}
}
}
But i need to be able to make this alias query dynamic based on the lenght of the array. How would you approach to solve this problem? Is it possible to maybe create a loop that will write out the query before i will run it. Any help to let me in the right direction here would be highly appreciated! Thank you!
ps. im using javascript.
For anyone curious i ended up being able to use .map to dynamically loop out the query and the run it :)
let query = `
query productBySku {
site {
${sku
.map(
(product: any, idx: number) =>
`pro${idx}: product(sku: "${product}") {
id
entityId
sku
name
}
`
)
.join('')}
}
}
`