UNPKG

contentful-management

Version:
69 lines (67 loc) 2.34 kB
function isOffsetBasedCollection(collection) { return 'total' in collection; } function isCursorBasedCollection(collection) { return 'pages' in collection; } function getSearchParam(url, paramName) { const searchIndex = url.indexOf('?'); if (searchIndex < 0) { return null; } const rawSearchParams = url.slice(searchIndex + 1); const searchParams = new URLSearchParams(rawSearchParams); return searchParams.get(paramName); } function range(from, to) { return Array.from(Array(Math.abs(to - from)), (_, i) => from + i); } /** * Parameters for endpoint methods that can be paginated are inconsistent, `fetchAll` will only * work with the more common version of supplying the limit, skip, and pageNext parameters via a distinct `query` property in the * parameters. */ async function fetchAll(fetchFn, params) { const response = await fetchFn({ ...params }); if (isOffsetBasedCollection(response)) { const { total, limit, items } = response; const hasMorePages = total > items.length; if (!hasMorePages) { return items; } const pageCount = Math.ceil(total / limit); const promises = range(1, pageCount).map((page) => fetchFn({ ...params, query: { ...params.query, limit, skip: page * limit, }, }).then((result) => result.items)); const remainingItems = await Promise.all(promises); return [...items, ...remainingItems.flat(1)]; } if (isCursorBasedCollection(response)) { const { pages, items } = response; if (!pages.next) { return items; } const pageNext = getSearchParam(pages.next, 'pageNext'); if (!pageNext) { throw new Error('Missing "pageNext" query param from pages.next from response.'); } return [ ...items, ...(await fetchAll(fetchFn, { ...params, query: { ...params.query, pageNext, }, })), ]; } throw new Error(`Can not determine collection type of response, neither property "total" nor "pages" are present.`); } export { fetchAll }; //# sourceMappingURL=pagination-helper.js.map