Skip to content

Commit

Permalink
implement/fix reverse iteration when iterating with ending_before (#1100
Browse files Browse the repository at this point in the history
)
  • Loading branch information
kaznovac authored Jan 7, 2021
1 parent ec960ea commit 0149aa5
Show file tree
Hide file tree
Showing 2 changed files with 644 additions and 417 deletions.
19 changes: 14 additions & 5 deletions lib/autoPagination.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const utils = require('./utils');

function makeAutoPaginationMethods(self, requestArgs, spec, firstPagePromise) {
const promiseCache = {currentPromise: null};
const reverseIteration = isReverseIteration(requestArgs);
let listPromise = firstPagePromise;
let i = 0;

Expand All @@ -22,15 +23,16 @@ function makeAutoPaginationMethods(self, requestArgs, spec, firstPagePromise) {
}

if (i < listResult.data.length) {
const value = listResult.data[i];
const idx = reverseIteration ? listResult.data.length - 1 - i : i;
const value = listResult.data[idx];
i += 1;
return {value, done: false};
} else if (listResult.has_more) {
// Reset counter, request next page, and recurse.
i = 0;
const lastId = getLastId(listResult);
const lastId = getLastId(listResult, reverseIteration);
listPromise = makeRequest(self, requestArgs, spec, {
starting_after: lastId,
[reverseIteration ? 'ending_before' : 'starting_after']: lastId,
});
return listPromise.then(iterate);
}
Expand Down Expand Up @@ -138,8 +140,8 @@ function getItemCallback(args) {
};
}

function getLastId(listResult) {
const lastIdx = listResult.data.length - 1;
function getLastId(listResult, reverseIteration) {
const lastIdx = reverseIteration ? 0 : listResult.data.length - 1;
const lastItem = listResult.data[lastIdx];
const lastId = lastItem && lastItem.id;
if (!lastId) {
Expand Down Expand Up @@ -241,3 +243,10 @@ function wrapAsyncIteratorWithCallback(asyncIteratorNext, onItem) {
.catch(reject);
});
}

function isReverseIteration(requestArgs) {
const args = [].slice.call(requestArgs);
const dataFromArgs = utils.getDataFromArgs(args);

return !!dataFromArgs.ending_before;
}
Loading

0 comments on commit 0149aa5

Please sign in to comment.