-
Notifications
You must be signed in to change notification settings - Fork 112
Pagination
Ariel Rey edited this page Jan 20, 2017
·
3 revisions
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. This seems to much work. To solve this, we inject two methods to the response:
- next: returns a Promise() and also receives a callback
- hasNext: returns a boolean
With this, you can check if the results have a next page and actually get it. Let's see an example:
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.