contentful-management
Version:
Client for Contentful's Content Management API
69 lines (66 loc) • 2.33 kB
JavaScript
import { toPlainObject } from 'contentful-sdk-core';
import copy from 'fast-copy';
/**
* @internal
*/
const wrapCollection = (fn) => (makeRequest, data, ...rest) => {
const collectionData = toPlainObject(copy(data));
// @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
// @ts-expect-error
return collectionData;
};
const wrapCursorPaginatedCollection = (fn) => (makeRequest, data, ...rest) => {
const collectionData = toPlainObject(copy(data));
// @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
// @ts-expect-error
return collectionData;
};
function isSuccessful(statusCode) {
return statusCode < 300;
}
function shouldRePoll(statusCode) {
return [404, 422, 429, 400].includes(statusCode);
}
async function waitFor(ms = 1000) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function normalizeCursorPaginationParameters(query) {
const { pagePrev, pageNext, ...rest } = query;
return {
...rest,
cursor: true,
// omit pagePrev and pageNext if the value is falsy
...(pagePrev ? { pagePrev } : null),
...(pageNext ? { pageNext } : null),
};
}
function extractQueryParam(key, url) {
if (!url)
return;
const queryIndex = url.indexOf('?');
if (queryIndex === -1)
return;
const queryString = url.slice(queryIndex + 1);
return new URLSearchParams(queryString).get(key) ?? undefined;
}
const Pages = {
prev: 'pagePrev',
next: 'pageNext',
};
const PAGE_KEYS = ['prev', 'next'];
function normalizeCursorPaginationResponse(data) {
const pages = {};
for (const key of PAGE_KEYS) {
const token = extractQueryParam(Pages[key], data.pages?.[key]);
if (token)
pages[key] = token;
}
return {
...data,
pages,
};
}
export { isSuccessful, normalizeCursorPaginationParameters, normalizeCursorPaginationResponse, shouldRePoll, waitFor, wrapCollection, wrapCursorPaginatedCollection };
//# sourceMappingURL=common-utils.js.map