You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fetch all products by a tag with Shopify Graphql #358
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);
Activity
Jore commentedon Oct 5, 2021
You are a legend!
mendiolarocky commentedon Sep 21, 2023
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".