This commit is contained in:
Convly 2022-02-18 14:36:39 +01:00
parent 51e1f762c1
commit 751631e3d8

View File

@ -146,53 +146,77 @@ const convertPopulateQueryParams = (populate, schema, depth = 0) => {
); );
} }
if (_.isPlainObject(populate)) {
return convertPopulateObject(populate, schema);
}
throw new InvalidPopulateError();
};
const convertPopulateObject = (populate, schema) => {
if (!schema) {
return {};
}
const { attributes } = schema; const { attributes } = schema;
if (_.isPlainObject(populate)) { return Object.entries(populate).reduce((acc, [key, subPopulate]) => {
const transformedPopulate = {};
for (const key in populate) {
const attribute = attributes[key]; const attribute = attributes[key];
const subPopulate = populate[key];
if (!attribute) { if (!attribute) {
continue; return acc;
} }
// Retrieve the target schema UID. // TODO: This is a temporary solution for dynamic zones that should be
// This flows only handle basic relations and component since it's // fixed when we'll implement a more accurate way to query dynamic zones
// not possible to populate with params for a dynamic zone or polymorphic relations. if (attribute.type === 'dynamiczone') {
const generatedFakeDynamicZoneSchema = {
uid: `${schema.uid}.${key}`,
attributes: attribute.components
.map(uid => strapi.getModel(uid))
.map(component => component.attributes)
.reduce((acc, componentAttributes) => ({ ...acc, ...componentAttributes }), {}),
};
return {
...acc,
[key]: convertNestedPopulate(subPopulate, generatedFakeDynamicZoneSchema),
};
}
if (attribute.type === 'media') {
const fileSchema = strapi.getModel('plugin::upoad.file');
return {
...acc,
[key]: convertNestedPopulate(subPopulate, fileSchema),
};
}
// NOTE: Retrieve the target schema UID.
// Only handles basic relations and component since it's not possible
// to populate with options for a dynamic zone or a polymorphic relation
let targetSchemaUID; let targetSchemaUID;
// Relations
if (attribute.type === 'relation') { if (attribute.type === 'relation') {
targetSchemaUID = attribute.target; targetSchemaUID = attribute.target;
} } else if (attribute.type === 'component') {
// Components
else if (attribute.type === 'component') {
targetSchemaUID = attribute.component; targetSchemaUID = attribute.component;
} } else {
return acc;
// Fallback
else {
continue;
} }
const targetSchema = strapi.getModel(targetSchemaUID); const targetSchema = strapi.getModel(targetSchemaUID);
if (!targetSchema) { if (!targetSchema) {
continue; return acc;
} }
transformedPopulate[key] = convertNestedPopulate(subPopulate, targetSchema); return {
} ...acc,
[key]: convertNestedPopulate(subPopulate, targetSchema),
return transformedPopulate; };
} }, {});
throw new InvalidPopulateError();
}; };
const convertNestedPopulate = (subPopulate, schema) => { const convertNestedPopulate = (subPopulate, schema) => {