Skip to content

Instantly share code, notes, and snippets.

@miketromba
Last active January 10, 2022 16:43
Show Gist options
  • Save miketromba/01c8b587d87eb84cfc3e417ec23d934b to your computer and use it in GitHub Desktop.
Save miketromba/01c8b587d87eb84cfc3e417ec23d934b to your computer and use it in GitHub Desktop.
PaginationTraverser.js
// 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