2019-08-21 12:10:23 +02:00
|
|
|
'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;
|
|
|
|
|
2019-10-04 11:38:54 +02:00
|
|
|
if (typeof plainData !== 'object') return plainData;
|
|
|
|
|
2019-08-21 12:10:23 +02:00
|
|
|
const attributes = model.attributes;
|
2019-09-20 09:56:00 +02:00
|
|
|
return Object.keys(plainData).reduce((acc, key) => {
|
2019-08-21 12:10:23 +02:00
|
|
|
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')
|
2019-08-21 12:10:23 +02:00
|
|
|
) {
|
|
|
|
const targetName =
|
2019-10-22 18:01:03 +02:00
|
|
|
attribute.model || attribute.collection || attribute.component;
|
2019-08-21 12:10:23 +02:00
|
|
|
|
|
|
|
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 =>
|
2019-08-21 12:10:23 +02:00
|
|
|
sanitizeEntity(entity, { model: targetModel, withPrivate })
|
|
|
|
)
|
2019-09-20 09:56:00 +02:00
|
|
|
: sanitizeEntity(plainData[key], { model: targetModel, withPrivate });
|
2019-08-21 12:10:23 +02:00
|
|
|
|
|
|
|
return acc;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-20 09:56:00 +02:00
|
|
|
acc[key] = plainData[key];
|
2019-08-21 12:10:23 +02:00
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
};
|