|
| 1 | +const { isEmpty, merge } = require("lodash/fp"); |
| 2 | + |
| 3 | +const extractModelAttributes = (model) => { |
| 4 | + // Remove 'related' field for 'upload.file', return other attributes. |
| 5 | + if (model.uid === "plugin::upload.file") { |
| 6 | + const { related, ...attributes } = model.attributes; |
| 7 | + return attributes; |
| 8 | + } |
| 9 | + return model.attributes; |
| 10 | +}; |
| 11 | + |
| 12 | +const buildPopulateTree = (modelUid, maxDepth = 20, ignore = []) => { |
| 13 | + const skipCreatorFields = strapi |
| 14 | + .plugin('strapi-plugin-nested-populator') |
| 15 | + ?.config('skipCreatorFields'); |
| 16 | + |
| 17 | + // Base conditions to terminate recursion. |
| 18 | + if (maxDepth <= 1) return true; |
| 19 | + if (modelUid === "admin::user" && skipCreatorFields) return undefined; |
| 20 | + |
| 21 | + const populate = {}; |
| 22 | + const model = strapi.getModel(modelUid); |
| 23 | + |
| 24 | + // Add model's collection name to ignore list if not already present. |
| 25 | + if (!ignore.includes(model.collectionName)) { |
| 26 | + ignore.push(model.collectionName); |
| 27 | + } |
| 28 | + |
| 29 | + for (const [key, value] of Object.entries(extractModelAttributes(model))) { |
| 30 | + if (ignore.includes(key)) continue; |
| 31 | + |
| 32 | + if (value) { |
| 33 | + switch (value.type) { |
| 34 | + case "component": |
| 35 | + populate[key] = buildPopulateTree(value.component, maxDepth - 1); |
| 36 | + break; |
| 37 | + |
| 38 | + case "dynamiczone": |
| 39 | + const dynamicPopulate = value.components.reduce((acc, comp) => { |
| 40 | + const componentPopulate = buildPopulateTree(comp, maxDepth - 1); |
| 41 | + return componentPopulate === true ? acc : merge(acc, componentPopulate); |
| 42 | + }, {}); |
| 43 | + populate[key] = isEmpty(dynamicPopulate) ? true : dynamicPopulate; |
| 44 | + break; |
| 45 | + |
| 46 | + case "relation": |
| 47 | + const relationPopulate = buildPopulateTree( |
| 48 | + value.target, |
| 49 | + key === "localizations" && maxDepth > 2 ? 1 : maxDepth - 1, |
| 50 | + ignore |
| 51 | + ); |
| 52 | + if (relationPopulate) { |
| 53 | + populate[key] = relationPopulate; |
| 54 | + } |
| 55 | + break; |
| 56 | + |
| 57 | + case "media": |
| 58 | + populate[key] = true; |
| 59 | + break; |
| 60 | + |
| 61 | + default: |
| 62 | + break; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Return the full populate object or true if no populates were added. |
| 68 | + return isEmpty(populate) ? true : { populate }; |
| 69 | +}; |
| 70 | + |
| 71 | +module.exports = { |
| 72 | + buildPopulateTree |
| 73 | +}; |
0 commit comments