strapi/packages/strapi-utils/lib/sanitize-entity.js

43 lines
1.2 KiB
JavaScript
Raw Normal View History

'use strict';
module.exports = function sanitizeEntity(data, { model, withPrivate = false }) {
if (typeof data !== 'object' || data == null) return data;
2019-09-20 09:56:00 +02:00
let plainData = typeof data.toJSON === 'function' ? data.toJSON() : data;
if (typeof plainData !== 'object') return plainData;
const attributes = model.attributes;
2019-09-20 09:56:00 +02:00
return Object.keys(plainData).reduce((acc, key) => {
const attribute = attributes[key];
if (attribute && attribute.private === true && withPrivate !== true) {
return acc;
}
if (
attribute &&
2019-10-22 18:01:03 +02:00
(attribute.model ||
attribute.collection ||
attribute.type === 'component')
) {
const targetName =
2019-10-22 18:01:03 +02:00
attribute.model || attribute.collection || attribute.component;
const targetModel = strapi.getModel(targetName, attribute.plugin);
2019-09-20 09:56:00 +02:00
if (targetModel && plainData[key] !== null) {
acc[key] = Array.isArray(plainData[key])
? plainData[key].map(entity =>
sanitizeEntity(entity, { model: targetModel, withPrivate })
)
2019-09-20 09:56:00 +02:00
: sanitizeEntity(plainData[key], { model: targetModel, withPrivate });
return acc;
}
}
2019-09-20 09:56:00 +02:00
acc[key] = plainData[key];
return acc;
}, {});
};