UNPKG

@itxch/contentful-import

Version:

This tool allows you to import JSON dump exported by contentful-export

90 lines (89 loc) 3.04 kB
"use strict"; const collection_js = require("lodash-es/collection.js"); const _o = require("lodash-es/object.js"); const array_js = require("lodash-es/array.js"); function _interopNamespaceDefault(e) { const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } }); if (e) { for (const k in e) { if (k !== "default") { const d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: () => e[k] }); } } } n.default = e; return Object.freeze(n); } const _o__namespace = /* @__PURE__ */ _interopNamespaceDefault(_o); function sortEntries(entries) { const linkedEntries = getLinkedEntries(entries); const mergedLinkedEntries = mergeSort(linkedEntries, (a) => { return hasLinkedIndexesInFront(a); }); return collection_js.map(mergedLinkedEntries, (linkInfo) => entries[linkInfo.index]); function hasLinkedIndexesInFront(item) { if (hasLinkedIndexes(item)) { return collection_js.some(item.linkIndexes, (index) => index > item.index) ? 1 : -1; } return 0; } function hasLinkedIndexes(item) { return item.linkIndexes.length > 0; } } function getLinkedEntries(entries) { return collection_js.map(entries, function(entry) { const entryIndex = entries.indexOf(entry); const rawLinks = collection_js.map(entry.fields, (field) => { field = _o__namespace.values(field)[0]; if (isEntryLink(field)) { return getFieldEntriesIndex(field, entries); } else if (isEntityArray(field) && isEntryLink(field[0])) { return collection_js.map(field, (item) => getFieldEntriesIndex(item, entries)); } }); return { index: entryIndex, linkIndexes: collection_js.filter(array_js.flatten(rawLinks), (index) => index >= 0) }; }); } function getFieldEntriesIndex(field, entries) { const id = _o__namespace.get(field, "sys.id"); return entries.findIndex((entry) => entry.sys.id === id); } function isEntryLink(item) { return _o__namespace.get(item, "sys.type") === "Entry" || _o__namespace.get(item, "sys.linkType") === "Entry"; } function isEntityArray(item) { return Array.isArray(item) && item.length > 0 && _o__namespace.has(item[0], "sys"); } function mergeSort(arr, compareFn) { if (arr.length < 2) return arr; if (compareFn == null) compareFn = defaultCompare; const mid = ~~(arr.length / 2); const left = mergeSort(arr.slice(0, mid), compareFn); const right = mergeSort(arr.slice(mid, arr.length), compareFn); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0; } function merge(left, right, compareFn) { const result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) result.push(...left); if (right.length) result.push(...right); return result; } module.exports = sortEntries;