payloadcms-import-export-plugin
Version:
A comprehensive Payload CMS plugin that enables seamless import and export of collection data with support for CSV and JSON formats, featuring advanced field mapping, duplicate handling, and batch processing capabilities.
108 lines (107 loc) • 4.71 kB
JavaScript
export const flattenObject = ({ doc, fields, prefix, toCSVFunctions })=>{
const row = {};
const flatten = (siblingDoc, prefix)=>{
Object.entries(siblingDoc).forEach(([key, value])=>{
const newKey = prefix ? `${prefix}_${key}` : key;
if (Array.isArray(value)) {
value.forEach((item, index)=>{
if (typeof item === 'object' && item !== null) {
// Case: hasMany polymorphic relationships
if ('relationTo' in item && 'value' in item && typeof item.value === 'object' && item.value !== null) {
row[`${`${newKey}_${index}`}_relationTo`] = item.relationTo;
row[`${`${newKey}_${index}`}_id`] = item.value.id;
return;
}
flatten(item, `${newKey}_${index}`);
} else {
if (toCSVFunctions?.[newKey]) {
const columnName = `${newKey}_${index}`;
try {
const result = toCSVFunctions[newKey]({
columnName,
data: row,
doc,
row,
siblingDoc,
value: item
});
if (typeof result !== 'undefined') {
row[columnName] = result;
}
} catch (error) {
throw new Error(`Error in toCSVFunction for array item "${columnName}": ${JSON.stringify(item)}\n${error.message}`);
}
} else {
row[`${newKey}_${index}`] = item;
}
}
});
} else if (typeof value === 'object' && value !== null) {
if (!toCSVFunctions?.[newKey]) {
flatten(value, newKey);
} else {
try {
const result = toCSVFunctions[newKey]({
columnName: newKey,
data: row,
doc,
row,
siblingDoc,
value
});
if (typeof result !== 'undefined') {
row[newKey] = result;
}
} catch (error) {
throw new Error(`Error in toCSVFunction for nested object "${newKey}": ${JSON.stringify(value)}\n${error.message}`);
}
}
} else {
if (toCSVFunctions?.[newKey]) {
try {
const result = toCSVFunctions[newKey]({
columnName: newKey,
data: row,
doc,
row,
siblingDoc,
value
});
if (typeof result !== 'undefined') {
row[newKey] = result;
}
} catch (error) {
throw new Error(`Error in toCSVFunction for field "${newKey}": ${JSON.stringify(value)}\n${error.message}`);
}
} else {
row[newKey] = value;
}
}
});
};
flatten(doc, prefix);
if (Array.isArray(fields) && fields.length > 0) {
const orderedResult = {};
const fieldToRegex = (field)=>{
const parts = field.split('.').map((part)=>`${part}(?:_\\d+)?`);
const pattern = `^${parts.join('_')}`;
return new RegExp(pattern);
};
fields.forEach((field)=>{
if (row[field.replace(/\./g, '_')]) {
const sanitizedField = field.replace(/\./g, '_');
orderedResult[sanitizedField] = row[sanitizedField];
} else {
const regex = fieldToRegex(field);
Object.keys(row).forEach((key)=>{
if (regex.test(key)) {
orderedResult[key] = row[key];
}
});
}
});
return orderedResult;
}
return row;
};
//# sourceMappingURL=flattenObject.js.map