Skip to content

Pagination

Ariel Rey edited this page Jan 24, 2017 · 3 revisions

Automatic Pagination Wrapper

There are some API endpoints that returns the response paginated. For example if you are searching for all the payments that were made for you. Let's see an example:

mercadopago.payment.search({
  qs: {
    'collector.id': 'me'
  }
}).then(function (mpResponse) {
  console.log(mpResponse);
});

The output is going to be this:

mercadopagoResponse {
  body: 
   { paging: { total: 110, limit: 30, offset: 0 },
     results: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ] },
  status: 200,
  idempotency: undefined,
  pagination: { total: 110, limit: 30, offset: 0 } }

As you can see, you have 100 payments, and 30 results per request.

Before, ff you wan't to get the next page, you need to manually execute the search again, like this:

mercadopago.payment.search({
  qs: {
    'collector.id': 'me',
    pagination: {
      offset: 30
    }
  }
}).then(function (mpResponse) {
  console.log(mpResponse);
});

Then, you receive the next page or de previous page. This seems to much work. To solve this, we inject two methods to the response:

  • next: returns a Promise() and also receives a callback with the next page
  • hasNext: returns a boolean if a next page exists
  • prev: returns a Promise() and also recieves a callback with the previous page
  • hasPrev: returns a boolean if a previous page exists

With this, you can check if the results have a next or previous page and actually get it. Let's see an example with next page:

mercadopago.payment.search({
  qs: {
    'collector.id': 'me'
  }
}).then(function (mpResponse) {
  if (mpResponse.hasNext()) {
    return mpRepsonse.next();
  }
}).then(function (nextPage) {
  console.log(nextPage);
});

You can use callbacks too:

mercadopago.payment.search({
  qs: {
    'collector.id': 'me'
  }
}, function(err, mpResponse) {
  if (mpResponse.hasNext()) {
    return mpRepsonse.next(function (nextPage) {
      console.log(nextPage);
    });
  }
});

Maybe you wan't to implement a recursive method to get all of your payments.

Clone this wiki locally