UNPKG

@dotcms/client

Version:

Official JavaScript library for interacting with DotCMS REST APIs.

90 lines (88 loc) 3 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ /** * Transforms a GraphQL Page response to a Page Entity. * * @param {GraphQLPageResponse} graphQLPageResponse - The GraphQL Page response object. * @returns {object|null} The transformed Page Entity or null if the page is not present. * * @example * ```ts * const pageEntity = graphqlToPageEntity(graphQLPageResponse); * ``` */ const graphqlToPageEntity = (graphQLPageResponse) => { const { page } = graphQLPageResponse; // If there is no page, return null if (!page) { return null; } const { layout, template, containers, urlContentMap, viewAs, host, vanityUrl, runningExperimentId, _map, ...pageAsset } = page; const data = (_map || {}); const typedPageAsset = pageAsset; // Merge all urlContentMap keys into _map, except _map itself const mergedUrlContentMap = { ...(urlContentMap?._map || {}), ...Object.entries(urlContentMap || {}).reduce((acc, [key, value]) => { if (key !== '_map') { acc[key] = value; } return acc; }, {}) }; return { layout, template, viewAs, vanityUrl, runningExperimentId, site: host, urlContentMap: mergedUrlContentMap, containers: parseContainers(containers), page: { ...data, ...typedPageAsset } }; }; /** * Parses the containers from the GraphQL response. * * @param {DotCMSGraphQLPageContainer[]} [containers=[]] - The containers array from the GraphQL response. * @returns {DotCMSPageAssetContainers} The parsed containers. */ const parseContainers = (containers = []) => { return containers.reduce((acc, container) => { const { path, identifier, containerStructures, containerContentlets, ...rest } = container; const key = (path || identifier); acc[key] = { containerStructures, container: { path, identifier, ...rest }, contentlets: parseContentletsToUuidMap(containerContentlets) }; return acc; }, {}); }; /** * Parses the contentlets from the GraphQL response. * * @param {Array<Record<string, unknown>>} containerContentlets - The contentlets array from the GraphQL response. * @returns {Record<string, Array<Record<string, unknown>>>} The parsed contentlets mapped by UUID. */ const parseContentletsToUuidMap = (containerContentlets = []) => { return containerContentlets.reduce((acc, containerContentlet) => { const { uuid, contentlets } = containerContentlet; // TODO: This is a temporary solution, we need to find a better way to handle this. acc[uuid] = contentlets.map(({ _map = {}, ...rest }) => { return { ..._map, ...rest }; }); return acc; }, {}); }; export { graphqlToPageEntity };