Cursor based pagination graphl

  graphql, javascript, koa

I am retrieving data from graphql over koa-server. For that I wrote a function requestData(token, queryName, cursor) to call the graphql.

I want to repeat the request until the cursor is null or undefined. I need to use always the last cursor:

lastCursor = edges[edges.length – 1].cursor;

In the terminal I am getting following outputs:

null
eyJsYXN0X2lkIjo2MTQzNTk3ODcxMjc0LCJsYXN0X3ZhbHVlIjoiNjE0MzU5Nzg3MTI3NCJ9

But nothing more even I have more data. Can someone help what is wrong in my code?

server.js part

  router.post('/getAllProducts', bodyParser(), async (ctx, next) => {
    let data;
    let edges;
    let lastCursor = null;
    const { accessToken } = ctx.session;
    ctx.response.status = 200;

    requestData(accessToken, GET_ALL_PRODUCTS, lastCursor).then((res) => {
      data = res.data.data;
      edges = data.products.edges;
      lastCursor = edges[edges.length - 1].cursor;
      setTimeout(() => {
        requestData(accessToken, GET_ALL_PRODUCTS, lastCursor);
      }, 1000);
    });
  });

  function requestData(token, queryName, cursor) {
    const variables = { after: cursor };
    console.log(cursor);
    const res = axios({
      headers: {
        'X-Shopify-Access-Token': token,
      },
      method: 'post',
      data: {
        query: queryName,
        variables: variables,
      },
      url: url,
    });

    return res;
  }

Source: Ask Javascript Questions

LEAVE A COMMENT