Skip to content

Fetch all products by a tag with Shopify Graphql #358

Open

Description

@coderapper

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!

Activity

  1. Jore commented on Oct 5, 2021

    @Jore

    You are a legend!

  2. mendiolarocky commented on Sep 21, 2023

    @mendiolarocky

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions