
Querying Shopify Storefront Data with the JavaScript Buy SDK
First, you will need to install the Shopify JavaScript Buy SDK. There is already decent documentation to do the basic things. However, it can be lacking in some parts when it comes to constructing more complex queries.
The Buy SDK allows you to construct the GraphQL query by leveraging their APIs. To construct more complicated queries, you will need to leverage the unoptimized SDK by importing it in your code
import Client from 'shopify-buy/index.unoptimized.umd';
Now let's look at how you would go about constructing a more complex query using the Buy SDK. I'm assuming in this case you have already instantiated the client somewhere by passing in whatever store access token your Shopify storefront provided you.
Let's say I want to make a table that contains all of the products and their variants. First, I would need to query for products, then query for each of their variants. We would need to add several connections.
const mainQuery = this.client.graphQLClient.query((root) => {
root.addConnection("products", { args: {first: 250} }, (product) => {
product.add("title");
product.add("handle");
product.add('tags');
product.addConnection("variants", { args: {first: 250}}, (variant) => {
variant.add('id');
variant.add("title");
variant.add("quantityAvailable");
variant.add('sku');
variant.add('priceV2', (price) => {
price.add('amount');
});
variant.add('image', (image) => {
image.add('url');
})
})
});
});
As of now Shopify only allows a maximum number of 250 entries. You can change this or leave it. You can see that we are querying the prices and the image for each of the variants along with other pieces of data.
Once you have this query, this is how you go about invoking it.
let promise = new Promise((resolve, reject) => {
client.graphQLClient.send(mainQuery).then(({ model, data }) => {
model.products.forEach((product) => {
product.variants.forEach((variant) => {
variantsArr.push(variant);
});
});
const hasMore = model.products.length === 0 ? false : model.products[model.products.length - 1].hasNextPage;
resolve({ variants: variantsArr, hasMore });
});
});
Here we loop through each product, and each variant on that product and add it to an array. We then return a promise to whatever invoked this method. You will notice the hasNextPage. Since we can only query a max of 250 entries, there might be more for us to query. If there is, then we essentially need to fetch the next page.
We call the following
client.fetchNextPage(myModel.products).then((products) => ...
We need to pass in the model.products that we got from the previous call when we initially sent our query.
And that's it! You may need to be cognizant about the storefront rate limits, however, I never encountered issues and I could easily query thousands of products and variants no problem. But it's always good to be aware of exactly how the Shopify API rate limits work.

