Paginations

When fetching connections, you need to specify exactly how many items you want to fetch. And higher limit will contribute to higher query cost and subject to rate limiting. Therefore, it's important to not request an unrealistically high limit.

What is better is start with a slightly lower limit, and fetch more items if necessary. this will require paginating the graphql requests. To do that you will need to request pageInfo and cursor properties in the query. See this guide for more details.

Here is an example of continuously fetching for more line items from an order until all items are fetched.


const PAGE_SIZE = 15;
let has_next_page = false;
let line_item_array = [];

// get all line items for the order
do {
  let after_query = '';

  // generate the `after` filter 
  if (has_next_page && line_item_array.length > 0) {
    const cursor = line_item_array[line_item_array.length - 1].cursor;
    after_query = `, after: "${cursor}"`;
  }

  const query = `{
    order(id: "${gql_order_id}") {
      lineItems(first: ${PAGE_SIZE} ${after_query}) {
        pageInfo{
          hasNextPage
        }
        edges {
          cursor
          node {
            sku
            quantity
            product {
              legacyResourceId
              tags
            }
          }
        }
      }
    }
  }`;
  const { order } = await shopify.graphql(query);

  line_item_array = line_item_array.concat(order.lineItems.edges);
  has_next_page = order.lineItems.pageInfo.hasNextPage;
} while (has_next_page);

Last updated