UNPKG

sb-mig

Version:

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

49 lines (48 loc) 1.88 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAllItemsWithPagination = void 0; const logger_js_1 = __importDefault(require("../../utils/logger.js")); 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_js_1.default.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_js_1.default.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; }; exports.getAllItemsWithPagination = getAllItemsWithPagination;