GraphQL Request Cursor Pagination

Fetch paginated GraphQL connections with graphql-request, following cursor edges and pageInfo detection until the full dataset is drained.

JavascriptData Fetching

Code

snippet
import { GraphQLClient, gql } from 'graphql-request';

const client = new GraphQLClient('https://api.example.com/graphql', {
  headers: { Authorization: 'Bearer ' + process.env.API_TOKEN },
});

const query = gql`
  query Orders($first: Int!, $after: String) {
    orders(first: $first, after: $after) {
      edges { cursor node { id total } }
      pageInfo { hasNextPage endCursor }
    }
  }
`;

async function fetchAllOrders(pageSize = 50) {
  const results = [];
  let after = null;

  while (true) {
    const data = await client.request(query, { first: pageSize, after });
    const { edges, pageInfo } = data.orders;
    results.push(...edges.map((edge) => edge.node));

    if (!pageInfo.hasNextPage) break;
    after = pageInfo.endCursor;
  }
  return results;
}

const orders = await fetchAllOrders();
console.log('total orders fetched:', orders.length);