@tokens-studio/sdk
Version:
The official SDK for Tokens Studio
29 lines • 1.24 kB
JavaScript
export async function fetchPaginatedData(client, query, variables) {
variables = (variables ?? {});
let data = [];
const fetchPage = async (page) => {
const pageData = await query(client, {
// typecast, because we add the page below on the next line
...variables,
page,
});
return pageData;
};
const firstBatch = await fetchPage(1);
data = [firstBatch.data];
if (firstBatch.totalPages > 1) {
// subsequent batches can be fetched in parallel, wait till all are done
const subsequentBatches = await Promise.all(
// create an array, 1 item per page that we haven't fetched yet
// -1 because we already fetched the first page
Array(firstBatch.totalPages - 1)
.fill(null)
// map each item to a Promise for fetching the data, initializes the fetching
// +1 because pages are 1-indexed, and another +1 because we fetched first page already
.map((_, i) => fetchPage(i + 2)));
const batchesData = subsequentBatches.map((batch) => batch.data);
data = [...data, ...batchesData];
}
return data.flat();
}
//# sourceMappingURL=fetch-paginated-data.js.map