Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch all products by a tag with Shopify Graphql #358

Open
coderapper opened this issue Mar 15, 2020 · 2 comments
Open

Fetch all products by a tag with Shopify Graphql #358

coderapper opened this issue Mar 15, 2020 · 2 comments

Comments

@coderapper
Copy link

coderapper commented Mar 15, 2020

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!

@Jore
Copy link

Jore commented Oct 5, 2021

You are a legend!

@mendiolarocky
Copy link

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants