Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement/fix reverse iteration when iterating with ending_before #1100

Merged
merged 6 commits into from
Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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