UNPKG

sb-mig

Version:

CLI to rule the world. (and handle stuff related to Storyblok CMS)

42 lines (41 loc) 1.51 kB
import Logger from "../../utils/logger.js"; export const getAllItemsWithPagination = async ({ apiFn, params, itemsKey, }) => { const per_page = 100; const allItems = []; let page = 1; let totalPages; let amountOfFetchedItems = 0; do { const response = await apiFn({ per_page, page, ...params }); // Handle case where API call failed and returned undefined if (!response || !response.data) { Logger.warning(`API returned no data for ${itemsKey}`); return allItems; } if (!totalPages) { totalPages = Math.ceil((response.total ?? 0) / (response.perPage ?? per_page)) || 1; } /** * * Not every endpoint in storyblok give us pagination... * so only for this who paginate we want to calculate values to show * * */ if (response.total) { amountOfFetchedItems += response.total - amountOfFetchedItems > per_page ? per_page : response.total - amountOfFetchedItems; if (amountOfFetchedItems && !Number.isNaN(amountOfFetchedItems)) { Logger.success(`${amountOfFetchedItems} of ${response.total} items fetched.`); } } const items = response.data?.[itemsKey]; if (Array.isArray(items)) { allItems.push(...items); } page++; } while (page <= totalPages); return allItems; };