Last active
January 10, 2022 16:43
-
-
Save miketromba/01c8b587d87eb84cfc3e417ec23d934b to your computer and use it in GitHub Desktop.
PaginationTraverser.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get all records from { page, limit } style pagination | |
// NOTE: this class assumes that the first page value is 1 (NOT 0) | |
// Tweak the class if your system begins pagination with page 0. | |
class PaginationTraverser { | |
constructor({ limit, getPage }){ | |
// Limit must not exceed server's clamp range or this breaks | |
// very badly (infinite while loop) | |
this.limit = limit | |
this.getPage = getPage | |
} | |
async getAll(){ | |
const allItems = [] | |
let page = 0 | |
let pageItems = [] | |
async function loadMore(){ | |
page++ | |
pageItems = await getPage(page) | |
pageItems.forEach(e => allItems.push(e)) | |
} | |
await loadMore() | |
while(pageItems.length == this.limit){ | |
await loadMore() | |
} | |
return allItems | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment