Shopify-api-node
Shopify-api-node copied to clipboard
Fetch all products by a tag with Shopify Graphql
Hi Everyone,
This is not related to any specific issue. I've been using Shopify-api-node
for a few of my projects and one of the challenges was to be able to find all products that have a specific tag with a graphql query. So while I was doing that I couldn't able to find any specific documentation on how to paginate the results with shopify-api-node
s graphql query. After a few attempts, I was able to paginate the results with following simple async function, so I thought it would be a good idea to share the solution here which others may find helpful since I saw multiple threads around this topic. here it is !
const query = `query($cursor: String){
products(first: 250, after:$cursor, query: "tag:tag_name") {
pageInfo {
hasNextPage
}
edges {
cursor
node {
id
tags
}
}
}
}
`
(async () => {
let hasNextPage = false;
let lastedge;
let variable;
do {
await shopify.graphql(query,variable).then((product) => {
counter = counter + 1;
const products = Object.values(product.products.edges);
for (const product of products) {
let id = product.node.id.split('/').slice(-1)[0];
counter = counter + 1; // to count the number of prodcuts
console.log(counter +"=>" +id+ "=>" +product.node.tags);
}
var last_key = product.products.edges.length;
lastedge = product.products.edges[last_key - 1].cursor;
hasNextPage = product.products.pageInfo.hasNextPage;
variable = {"cursor": lastedge};
});
} while (hasNextPage == true);
})().catch(console.error);
Cheers!
You are a legend!
The issue is that the result is not an exact match. When you need to fetch products with tag "test", it will also fetch products with tag "test 2".