@strapi/core 5.4.2 → 5.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Strapi.js +1 -2
- package/dist/Strapi.js.map +1 -1
- package/dist/Strapi.mjs.map +1 -1
- package/dist/compile.js.map +1 -1
- package/dist/compile.mjs.map +1 -1
- package/dist/configuration/config-loader.js +1 -2
- package/dist/configuration/config-loader.js.map +1 -1
- package/dist/configuration/config-loader.mjs +1 -2
- package/dist/configuration/config-loader.mjs.map +1 -1
- package/dist/configuration/get-dirs.js.map +1 -1
- package/dist/configuration/get-dirs.mjs.map +1 -1
- package/dist/configuration/index.d.ts.map +1 -1
- package/dist/configuration/index.js +8 -3
- package/dist/configuration/index.js.map +1 -1
- package/dist/configuration/index.mjs +8 -3
- package/dist/configuration/index.mjs.map +1 -1
- package/dist/configuration/urls.js.map +1 -1
- package/dist/configuration/urls.mjs.map +1 -1
- package/dist/container.js.map +1 -1
- package/dist/container.mjs.map +1 -1
- package/dist/core-api/controller/collection-type.js.map +1 -1
- package/dist/core-api/controller/collection-type.mjs.map +1 -1
- package/dist/core-api/controller/index.js.map +1 -1
- package/dist/core-api/controller/index.mjs.map +1 -1
- package/dist/core-api/controller/single-type.js.map +1 -1
- package/dist/core-api/controller/single-type.mjs.map +1 -1
- package/dist/core-api/controller/transform.js.map +1 -1
- package/dist/core-api/controller/transform.mjs.map +1 -1
- package/dist/core-api/routes/index.js.map +1 -1
- package/dist/core-api/routes/index.mjs.map +1 -1
- package/dist/core-api/service/collection-type.js.map +1 -1
- package/dist/core-api/service/collection-type.mjs.map +1 -1
- package/dist/core-api/service/core-service.js.map +1 -1
- package/dist/core-api/service/core-service.mjs.map +1 -1
- package/dist/core-api/service/index.js.map +1 -1
- package/dist/core-api/service/index.mjs.map +1 -1
- package/dist/core-api/service/pagination.js.map +1 -1
- package/dist/core-api/service/pagination.mjs.map +1 -1
- package/dist/core-api/service/single-type.js +1 -2
- package/dist/core-api/service/single-type.js.map +1 -1
- package/dist/core-api/service/single-type.mjs +1 -2
- package/dist/core-api/service/single-type.mjs.map +1 -1
- package/dist/domain/content-type/index.js.map +1 -1
- package/dist/domain/content-type/index.mjs.map +1 -1
- package/dist/domain/content-type/validator.js.map +1 -1
- package/dist/domain/content-type/validator.mjs.map +1 -1
- package/dist/domain/module/index.js.map +1 -1
- package/dist/domain/module/index.mjs.map +1 -1
- package/dist/domain/module/validation.js.map +1 -1
- package/dist/domain/module/validation.mjs.map +1 -1
- package/dist/ee/index.js.map +1 -1
- package/dist/ee/index.mjs.map +1 -1
- package/dist/ee/license.js.map +1 -1
- package/dist/ee/license.mjs.map +1 -1
- package/dist/factories.js.map +1 -1
- package/dist/factories.mjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/loaders/admin.js.map +1 -1
- package/dist/loaders/admin.mjs.map +1 -1
- package/dist/loaders/apis.js.map +1 -1
- package/dist/loaders/apis.mjs.map +1 -1
- package/dist/loaders/components.js.map +1 -1
- package/dist/loaders/components.mjs.map +1 -1
- package/dist/loaders/middlewares.js.map +1 -1
- package/dist/loaders/middlewares.mjs.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
- package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
- package/dist/loaders/plugins/get-user-plugins-config.mjs.map +1 -1
- package/dist/loaders/plugins/index.js +1 -2
- package/dist/loaders/plugins/index.js.map +1 -1
- package/dist/loaders/plugins/index.mjs.map +1 -1
- package/dist/loaders/policies.js.map +1 -1
- package/dist/loaders/policies.mjs.map +1 -1
- package/dist/loaders/sanitizers.js.map +1 -1
- package/dist/loaders/sanitizers.mjs.map +1 -1
- package/dist/loaders/src-index.js.map +1 -1
- package/dist/loaders/src-index.mjs.map +1 -1
- package/dist/loaders/validators.js.map +1 -1
- package/dist/loaders/validators.mjs.map +1 -1
- package/dist/middlewares/body.js.map +1 -1
- package/dist/middlewares/body.mjs.map +1 -1
- package/dist/middlewares/cors.js.map +1 -1
- package/dist/middlewares/cors.mjs.map +1 -1
- package/dist/middlewares/errors.js.map +1 -1
- package/dist/middlewares/errors.mjs.map +1 -1
- package/dist/middlewares/favicon.js.map +1 -1
- package/dist/middlewares/favicon.mjs.map +1 -1
- package/dist/middlewares/index.js.map +1 -1
- package/dist/middlewares/logger.js.map +1 -1
- package/dist/middlewares/logger.mjs.map +1 -1
- package/dist/middlewares/powered-by.js.map +1 -1
- package/dist/middlewares/powered-by.mjs.map +1 -1
- package/dist/middlewares/public.js.map +1 -1
- package/dist/middlewares/public.mjs.map +1 -1
- package/dist/middlewares/query.js.map +1 -1
- package/dist/middlewares/query.mjs.map +1 -1
- package/dist/middlewares/response-time.js.map +1 -1
- package/dist/middlewares/response-time.mjs.map +1 -1
- package/dist/middlewares/responses.js.map +1 -1
- package/dist/middlewares/responses.mjs.map +1 -1
- package/dist/middlewares/security.js.map +1 -1
- package/dist/middlewares/security.mjs.map +1 -1
- package/dist/middlewares/session.js.map +1 -1
- package/dist/middlewares/session.mjs.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
- package/dist/migrations/draft-publish.js.map +1 -1
- package/dist/migrations/draft-publish.mjs.map +1 -1
- package/dist/migrations/i18n.js.map +1 -1
- package/dist/migrations/i18n.mjs.map +1 -1
- package/dist/migrations/index.js.map +1 -1
- package/dist/migrations/index.mjs.map +1 -1
- package/dist/providers/admin.js.map +1 -1
- package/dist/providers/admin.mjs.map +1 -1
- package/dist/providers/coreStore.js.map +1 -1
- package/dist/providers/coreStore.mjs.map +1 -1
- package/dist/providers/cron.js.map +1 -1
- package/dist/providers/cron.mjs.map +1 -1
- package/dist/providers/registries.js.map +1 -1
- package/dist/providers/registries.mjs.map +1 -1
- package/dist/providers/telemetry.js.map +1 -1
- package/dist/providers/telemetry.mjs.map +1 -1
- package/dist/providers/webhooks.js.map +1 -1
- package/dist/providers/webhooks.mjs.map +1 -1
- package/dist/registries/apis.js.map +1 -1
- package/dist/registries/apis.mjs.map +1 -1
- package/dist/registries/components.js.map +1 -1
- package/dist/registries/components.mjs.map +1 -1
- package/dist/registries/content-types.js.map +1 -1
- package/dist/registries/content-types.mjs.map +1 -1
- package/dist/registries/controllers.js.map +1 -1
- package/dist/registries/controllers.mjs.map +1 -1
- package/dist/registries/custom-fields.js.map +1 -1
- package/dist/registries/custom-fields.mjs.map +1 -1
- package/dist/registries/hooks.js.map +1 -1
- package/dist/registries/hooks.mjs.map +1 -1
- package/dist/registries/middlewares.js.map +1 -1
- package/dist/registries/middlewares.mjs.map +1 -1
- package/dist/registries/models.js.map +1 -1
- package/dist/registries/models.mjs.map +1 -1
- package/dist/registries/modules.js.map +1 -1
- package/dist/registries/modules.mjs.map +1 -1
- package/dist/registries/namespace.js.map +1 -1
- package/dist/registries/namespace.mjs.map +1 -1
- package/dist/registries/plugins.js.map +1 -1
- package/dist/registries/plugins.mjs.map +1 -1
- package/dist/registries/policies.js.map +1 -1
- package/dist/registries/policies.mjs.map +1 -1
- package/dist/registries/sanitizers.js.map +1 -1
- package/dist/registries/sanitizers.mjs.map +1 -1
- package/dist/registries/services.js.map +1 -1
- package/dist/registries/services.mjs.map +1 -1
- package/dist/registries/validators.js.map +1 -1
- package/dist/registries/validators.mjs.map +1 -1
- package/dist/services/auth/index.js.map +1 -1
- package/dist/services/auth/index.mjs.map +1 -1
- package/dist/services/config.js.map +1 -1
- package/dist/services/config.mjs.map +1 -1
- package/dist/services/content-api/index.js.map +1 -1
- package/dist/services/content-api/index.mjs.map +1 -1
- package/dist/services/content-api/permissions/index.js.map +1 -1
- package/dist/services/content-api/permissions/index.mjs.map +1 -1
- package/dist/services/content-api/permissions/providers/action.js.map +1 -1
- package/dist/services/content-api/permissions/providers/action.mjs.map +1 -1
- package/dist/services/content-api/permissions/providers/condition.js.map +1 -1
- package/dist/services/content-api/permissions/providers/condition.mjs.map +1 -1
- package/dist/services/core-store.js.map +1 -1
- package/dist/services/core-store.mjs.map +1 -1
- package/dist/services/cron.js +1 -2
- package/dist/services/cron.js.map +1 -1
- package/dist/services/cron.mjs +1 -2
- package/dist/services/cron.mjs.map +1 -1
- package/dist/services/custom-fields.js.map +1 -1
- package/dist/services/custom-fields.mjs.map +1 -1
- package/dist/services/document-service/attributes/index.js.map +1 -1
- package/dist/services/document-service/attributes/index.mjs.map +1 -1
- package/dist/services/document-service/attributes/transforms.js.map +1 -1
- package/dist/services/document-service/attributes/transforms.mjs.map +1 -1
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/components.mjs.map +1 -1
- package/dist/services/document-service/draft-and-publish.js.map +1 -1
- package/dist/services/document-service/draft-and-publish.mjs.map +1 -1
- package/dist/services/document-service/entries.js.map +1 -1
- package/dist/services/document-service/entries.mjs.map +1 -1
- package/dist/services/document-service/events.js.map +1 -1
- package/dist/services/document-service/events.mjs.map +1 -1
- package/dist/services/document-service/index.js.map +1 -1
- package/dist/services/document-service/index.mjs.map +1 -1
- package/dist/services/document-service/internationalization.js.map +1 -1
- package/dist/services/document-service/internationalization.mjs.map +1 -1
- package/dist/services/document-service/middlewares/errors.js.map +1 -1
- package/dist/services/document-service/middlewares/errors.mjs.map +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
- package/dist/services/document-service/repository.js.map +1 -1
- package/dist/services/document-service/repository.mjs.map +1 -1
- package/dist/services/document-service/transform/data.js.map +1 -1
- package/dist/services/document-service/transform/data.mjs.map +1 -1
- package/dist/services/document-service/transform/fields.js.map +1 -1
- package/dist/services/document-service/transform/fields.mjs.map +1 -1
- package/dist/services/document-service/transform/id-map.js +2 -4
- package/dist/services/document-service/transform/id-map.js.map +1 -1
- package/dist/services/document-service/transform/id-map.mjs +2 -4
- package/dist/services/document-service/transform/id-map.mjs.map +1 -1
- package/dist/services/document-service/transform/id-transform.js.map +1 -1
- package/dist/services/document-service/transform/id-transform.mjs.map +1 -1
- package/dist/services/document-service/transform/populate.js.map +1 -1
- package/dist/services/document-service/transform/populate.mjs.map +1 -1
- package/dist/services/document-service/transform/query.js.map +1 -1
- package/dist/services/document-service/transform/query.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/extract/data-ids.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/transform/data-ids.js +1 -2
- package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/transform/data-ids.mjs +1 -2
- package/dist/services/document-service/transform/relations/transform/data-ids.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/transform/default-locale.js.map +1 -1
- package/dist/services/document-service/transform/relations/transform/default-locale.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/dp.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/utils/i18n.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/i18n.mjs.map +1 -1
- package/dist/services/document-service/transform/relations/utils/map-relation.js +3 -6
- package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/map-relation.mjs +3 -6
- package/dist/services/document-service/transform/relations/utils/map-relation.mjs.map +1 -1
- package/dist/services/document-service/utils/populate.js.map +1 -1
- package/dist/services/document-service/utils/populate.mjs.map +1 -1
- package/dist/services/document-service/utils/unidirectional-relations.js +1 -2
- package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -1
- package/dist/services/document-service/utils/unidirectional-relations.mjs +1 -2
- package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -1
- package/dist/services/entity-service/index.js.map +1 -1
- package/dist/services/entity-service/index.mjs.map +1 -1
- package/dist/services/entity-validator/blocks-validator.js.map +1 -1
- package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs.map +1 -1
- package/dist/services/errors.js.map +1 -1
- package/dist/services/errors.mjs.map +1 -1
- package/dist/services/event-hub.js.map +1 -1
- package/dist/services/event-hub.mjs.map +1 -1
- package/dist/services/features.js.map +1 -1
- package/dist/services/features.mjs.map +1 -1
- package/dist/services/fs.js.map +1 -1
- package/dist/services/fs.mjs.map +1 -1
- package/dist/services/metrics/admin-user-hash.js.map +1 -1
- package/dist/services/metrics/admin-user-hash.mjs.map +1 -1
- package/dist/services/metrics/index.js +1 -2
- package/dist/services/metrics/index.js.map +1 -1
- package/dist/services/metrics/index.mjs +1 -2
- package/dist/services/metrics/index.mjs.map +1 -1
- package/dist/services/metrics/is-truthy.js.map +1 -1
- package/dist/services/metrics/middleware.js.map +1 -1
- package/dist/services/metrics/middleware.mjs.map +1 -1
- package/dist/services/metrics/rate-limiter.js.map +1 -1
- package/dist/services/metrics/rate-limiter.mjs.map +1 -1
- package/dist/services/metrics/sender.js.map +1 -1
- package/dist/services/metrics/sender.mjs.map +1 -1
- package/dist/services/query-params.js.map +1 -1
- package/dist/services/query-params.mjs.map +1 -1
- package/dist/services/reloader.js.map +1 -1
- package/dist/services/reloader.mjs.map +1 -1
- package/dist/services/request-context.js.map +1 -1
- package/dist/services/request-context.mjs.map +1 -1
- package/dist/services/server/admin-api.js.map +1 -1
- package/dist/services/server/admin-api.mjs.map +1 -1
- package/dist/services/server/api.js.map +1 -1
- package/dist/services/server/api.mjs.map +1 -1
- package/dist/services/server/compose-endpoint.js.map +1 -1
- package/dist/services/server/compose-endpoint.mjs.map +1 -1
- package/dist/services/server/content-api.js.map +1 -1
- package/dist/services/server/content-api.mjs.map +1 -1
- package/dist/services/server/http-server.js.map +1 -1
- package/dist/services/server/http-server.mjs.map +1 -1
- package/dist/services/server/index.js.map +1 -1
- package/dist/services/server/index.mjs.map +1 -1
- package/dist/services/server/koa.js.map +1 -1
- package/dist/services/server/koa.mjs.map +1 -1
- package/dist/services/server/middleware.js.map +1 -1
- package/dist/services/server/middleware.mjs.map +1 -1
- package/dist/services/server/policy.js.map +1 -1
- package/dist/services/server/policy.mjs.map +1 -1
- package/dist/services/server/register-middlewares.js.map +1 -1
- package/dist/services/server/register-middlewares.mjs.map +1 -1
- package/dist/services/server/register-routes.js.map +1 -1
- package/dist/services/server/register-routes.mjs.map +1 -1
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/server/routing.mjs.map +1 -1
- package/dist/services/utils/dynamic-zones.js.map +1 -1
- package/dist/services/utils/dynamic-zones.mjs.map +1 -1
- package/dist/services/webhook-runner.js.map +1 -1
- package/dist/services/webhook-runner.mjs.map +1 -1
- package/dist/services/webhook-store.js.map +1 -1
- package/dist/services/webhook-store.mjs.map +1 -1
- package/dist/services/worker-queue.js.map +1 -1
- package/dist/services/worker-queue.mjs.map +1 -1
- package/dist/utils/convert-custom-field-type.js.map +1 -1
- package/dist/utils/convert-custom-field-type.mjs.map +1 -1
- package/dist/utils/cron.js.map +1 -1
- package/dist/utils/cron.mjs.map +1 -1
- package/dist/utils/fetch.js.map +1 -1
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/filepath-to-prop-path.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
- package/dist/utils/is-initialized.js.map +1 -1
- package/dist/utils/is-initialized.mjs.map +1 -1
- package/dist/utils/load-config-file.js.map +1 -1
- package/dist/utils/load-config-file.mjs.map +1 -1
- package/dist/utils/load-files.js +1 -2
- package/dist/utils/load-files.js.map +1 -1
- package/dist/utils/load-files.mjs +1 -2
- package/dist/utils/load-files.mjs.map +1 -1
- package/dist/utils/resolve-working-dirs.js.map +1 -1
- package/dist/utils/resolve-working-dirs.mjs.map +1 -1
- package/dist/utils/signals.js.map +1 -1
- package/dist/utils/signals.mjs.map +1 -1
- package/dist/utils/startup-logger.js.map +1 -1
- package/dist/utils/startup-logger.mjs.map +1 -1
- package/dist/utils/transform-content-types-to-models.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
- package/dist/utils/update-notifier/index.js.map +1 -1
- package/dist/utils/update-notifier/index.mjs.map +1 -1
- package/package.json +14 -15
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"unidirectional-relations.js","sources":["../../../../src/services/document-service/utils/unidirectional-relations.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport { keyBy, omit } from 'lodash/fp';\n\nimport { UID, Schema } from '@strapi/types';\n\ninterface LoadContext {\n oldVersions: { id: string; locale: string }[];\n newVersions: { id: string; locale: string }[];\n}\n\n/**\n * Loads lingering relations that need to be updated when overriding a published or draft entry.\n * This is necessary because the relations are uni-directional and the target entry is not aware of the source entry.\n * This is not the case for bi-directional relations, where the target entry is also linked to the source entry.\n */\nconst load = async (uid: UID.ContentType, { oldVersions, newVersions }: LoadContext) => {\n const updates = [] as any;\n\n // Iterate all components and content types to find relations that need to be updated\n await strapi.db.transaction(async ({ trx }) => {\n const contentTypes = Object.values(strapi.contentTypes) as Schema.ContentType[];\n const components = Object.values(strapi.components) as Schema.Component[];\n\n for (const model of [...contentTypes, ...components]) {\n const dbModel = strapi.db.metadata.get(model.uid);\n\n for (const attribute of Object.values(dbModel.attributes) as any) {\n /**\n * Only consider unidirectional relations\n */\n if (\n attribute.type !== 'relation' ||\n attribute.target !== uid ||\n attribute.inversedBy ||\n attribute.mappedBy\n ) {\n continue;\n }\n\n // TODO: joinColumn relations\n const joinTable = attribute.joinTable;\n if (!joinTable) {\n continue;\n }\n\n const { name: sourceColumnName } = joinTable.joinColumn;\n const { name: targetColumnName } = joinTable.inverseJoinColumn;\n\n /**\n * Load all relations that need to be updated\n */\n // NOTE: when the model has draft and publish, we can assume relation are only draft to draft & published to published\n const ids = oldVersions.map((entry) => entry.id);\n\n const oldVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (oldVersionsRelations.length > 0) {\n updates.push({ joinTable, relations: oldVersionsRelations });\n }\n\n /**\n * if publishing\n * if published version exists\n * updated published versions links\n * else\n * create link to newly published version\n *\n * if discarding\n * if published version link exists & not draft version link\n * create link to new draft version\n */\n\n if (!model.options?.draftAndPublish) {\n const ids = newVersions.map((entry) => entry.id);\n\n const newVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (newVersionsRelations.length > 0) {\n // when publishing a draft that doesn't have a published version yet,\n // copy the links to the draft over to the published version\n // when discarding a published version, if no drafts exists\n const discardToAdd = newVersionsRelations\n .filter((relation) => {\n const matchingOldVerion = oldVersionsRelations.find((oldRelation) => {\n return oldRelation[sourceColumnName] === relation[sourceColumnName];\n });\n\n return !matchingOldVerion;\n })\n .map(omit('id'));\n\n updates.push({ joinTable, relations: discardToAdd });\n }\n }\n }\n }\n });\n\n return updates;\n};\n\n/**\n * Updates uni directional relations to target the right entries when overriding published or draft entries.\n *\n * @param oldEntries The old entries that are being overridden\n * @param newEntries The new entries that are overriding the old ones\n * @param oldRelations The relations that were previously loaded with `load` @see load\n */\nconst sync = async (\n oldEntries: { id: string; locale: string }[],\n newEntries: { id: string; locale: string }[],\n oldRelations: { joinTable: any; relations: any[] }[]\n) => {\n /**\n * Create a map of old entry ids to new entry ids\n *\n * Will be used to update the relation target ids\n */\n const newEntryByLocale = keyBy('locale', newEntries);\n const oldEntriesMap = oldEntries.reduce(\n (acc, entry) => {\n const newEntry = newEntryByLocale[entry.locale];\n if (!newEntry) return acc;\n acc[entry.id] = newEntry.id;\n return acc;\n },\n {} as Record<string, string>\n );\n\n await strapi.db.transaction(async ({ trx }) => {\n // Iterate old relations that are deleted and insert the new ones\n for (const { joinTable, relations } of oldRelations) {\n // Update old ids with the new ones\n const column = joinTable.inverseJoinColumn.name;\n\n const newRelations = relations.map((relation) => {\n const newId = oldEntriesMap[relation[column]];\n return { ...relation, [column]: newId };\n });\n\n // Insert those relations into the join table\n await trx.batchInsert(joinTable.name, newRelations, 1000);\n }\n });\n};\n\nexport { load, sync };\n"],"names":["ids","omit","keyBy"],"mappings":";;;AAeA,MAAM,OAAO,OAAO,KAAsB,EAAE,aAAa,kBAA+B;AACtF,QAAM,UAAU,
|
1
|
+
{"version":3,"file":"unidirectional-relations.js","sources":["../../../../src/services/document-service/utils/unidirectional-relations.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport { keyBy, omit } from 'lodash/fp';\n\nimport { UID, Schema } from '@strapi/types';\n\ninterface LoadContext {\n oldVersions: { id: string; locale: string }[];\n newVersions: { id: string; locale: string }[];\n}\n\n/**\n * Loads lingering relations that need to be updated when overriding a published or draft entry.\n * This is necessary because the relations are uni-directional and the target entry is not aware of the source entry.\n * This is not the case for bi-directional relations, where the target entry is also linked to the source entry.\n */\nconst load = async (uid: UID.ContentType, { oldVersions, newVersions }: LoadContext) => {\n const updates = [] as any;\n\n // Iterate all components and content types to find relations that need to be updated\n await strapi.db.transaction(async ({ trx }) => {\n const contentTypes = Object.values(strapi.contentTypes) as Schema.ContentType[];\n const components = Object.values(strapi.components) as Schema.Component[];\n\n for (const model of [...contentTypes, ...components]) {\n const dbModel = strapi.db.metadata.get(model.uid);\n\n for (const attribute of Object.values(dbModel.attributes) as any) {\n /**\n * Only consider unidirectional relations\n */\n if (\n attribute.type !== 'relation' ||\n attribute.target !== uid ||\n attribute.inversedBy ||\n attribute.mappedBy\n ) {\n continue;\n }\n\n // TODO: joinColumn relations\n const joinTable = attribute.joinTable;\n if (!joinTable) {\n continue;\n }\n\n const { name: sourceColumnName } = joinTable.joinColumn;\n const { name: targetColumnName } = joinTable.inverseJoinColumn;\n\n /**\n * Load all relations that need to be updated\n */\n // NOTE: when the model has draft and publish, we can assume relation are only draft to draft & published to published\n const ids = oldVersions.map((entry) => entry.id);\n\n const oldVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (oldVersionsRelations.length > 0) {\n updates.push({ joinTable, relations: oldVersionsRelations });\n }\n\n /**\n * if publishing\n * if published version exists\n * updated published versions links\n * else\n * create link to newly published version\n *\n * if discarding\n * if published version link exists & not draft version link\n * create link to new draft version\n */\n\n if (!model.options?.draftAndPublish) {\n const ids = newVersions.map((entry) => entry.id);\n\n const newVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (newVersionsRelations.length > 0) {\n // when publishing a draft that doesn't have a published version yet,\n // copy the links to the draft over to the published version\n // when discarding a published version, if no drafts exists\n const discardToAdd = newVersionsRelations\n .filter((relation) => {\n const matchingOldVerion = oldVersionsRelations.find((oldRelation) => {\n return oldRelation[sourceColumnName] === relation[sourceColumnName];\n });\n\n return !matchingOldVerion;\n })\n .map(omit('id'));\n\n updates.push({ joinTable, relations: discardToAdd });\n }\n }\n }\n }\n });\n\n return updates;\n};\n\n/**\n * Updates uni directional relations to target the right entries when overriding published or draft entries.\n *\n * @param oldEntries The old entries that are being overridden\n * @param newEntries The new entries that are overriding the old ones\n * @param oldRelations The relations that were previously loaded with `load` @see load\n */\nconst sync = async (\n oldEntries: { id: string; locale: string }[],\n newEntries: { id: string; locale: string }[],\n oldRelations: { joinTable: any; relations: any[] }[]\n) => {\n /**\n * Create a map of old entry ids to new entry ids\n *\n * Will be used to update the relation target ids\n */\n const newEntryByLocale = keyBy('locale', newEntries);\n const oldEntriesMap = oldEntries.reduce(\n (acc, entry) => {\n const newEntry = newEntryByLocale[entry.locale];\n if (!newEntry) return acc;\n acc[entry.id] = newEntry.id;\n return acc;\n },\n {} as Record<string, string>\n );\n\n await strapi.db.transaction(async ({ trx }) => {\n // Iterate old relations that are deleted and insert the new ones\n for (const { joinTable, relations } of oldRelations) {\n // Update old ids with the new ones\n const column = joinTable.inverseJoinColumn.name;\n\n const newRelations = relations.map((relation) => {\n const newId = oldEntriesMap[relation[column]];\n return { ...relation, [column]: newId };\n });\n\n // Insert those relations into the join table\n await trx.batchInsert(joinTable.name, newRelations, 1000);\n }\n });\n};\n\nexport { load, sync };\n"],"names":["ids","omit","keyBy"],"mappings":";;;AAeA,MAAM,OAAO,OAAO,KAAsB,EAAE,aAAa,kBAA+B;AACtF,QAAM,UAAU,CAAC;AAGjB,QAAM,OAAO,GAAG,YAAY,OAAO,EAAE,UAAU;AAC7C,UAAM,eAAe,OAAO,OAAO,OAAO,YAAY;AACtD,UAAM,aAAa,OAAO,OAAO,OAAO,UAAU;AAElD,eAAW,SAAS,CAAC,GAAG,cAAc,GAAG,UAAU,GAAG;AACpD,YAAM,UAAU,OAAO,GAAG,SAAS,IAAI,MAAM,GAAG;AAEhD,iBAAW,aAAa,OAAO,OAAO,QAAQ,UAAU,GAAU;AAK9D,YAAA,UAAU,SAAS,cACnB,UAAU,WAAW,OACrB,UAAU,cACV,UAAU,UACV;AACA;AAAA,QAAA;AAIF,cAAM,YAAY,UAAU;AAC5B,YAAI,CAAC,WAAW;AACd;AAAA,QAAA;AAGF,cAAM,EAAE,MAAM,iBAAiB,IAAI,UAAU;AAC7C,cAAM,EAAE,MAAM,iBAAiB,IAAI,UAAU;AAM7C,cAAM,MAAM,YAAY,IAAI,CAAC,UAAU,MAAM,EAAE;AAE/C,cAAM,uBAAuB,MAAM,OAAO,GACvC,cAAc,EACd,OAAO,GAAG,EACV,KAAK,UAAU,IAAI,EACnB,QAAQ,kBAAkB,GAAG,EAC7B,YAAY,GAAG;AAEd,YAAA,qBAAqB,SAAS,GAAG;AACnC,kBAAQ,KAAK,EAAE,WAAW,WAAW,sBAAsB;AAAA,QAAA;AAezD,YAAA,CAAC,MAAM,SAAS,iBAAiB;AACnC,gBAAMA,OAAM,YAAY,IAAI,CAAC,UAAU,MAAM,EAAE;AAE/C,gBAAM,uBAAuB,MAAM,OAAO,GACvC,cAAc,EACd,OAAO,GAAG,EACV,KAAK,UAAU,IAAI,EACnB,QAAQ,kBAAkBA,IAAG,EAC7B,YAAY,GAAG;AAEd,cAAA,qBAAqB,SAAS,GAAG;AAInC,kBAAM,eAAe,qBAClB,OAAO,CAAC,aAAa;AACpB,oBAAM,oBAAoB,qBAAqB,KAAK,CAAC,gBAAgB;AACnE,uBAAO,YAAY,gBAAgB,MAAM,SAAS,gBAAgB;AAAA,cAAA,CACnE;AAED,qBAAO,CAAC;AAAA,YACT,CAAA,EACA,IAAIC,QAAK,IAAI,CAAC;AAEjB,oBAAQ,KAAK,EAAE,WAAW,WAAW,cAAc;AAAA,UAAA;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;AASA,MAAM,OAAO,OACX,YACA,YACA,iBACG;AAMG,QAAA,mBAAmBC,GAAAA,MAAM,UAAU,UAAU;AACnD,QAAM,gBAAgB,WAAW;AAAA,IAC/B,CAAC,KAAK,UAAU;AACR,YAAA,WAAW,iBAAiB,MAAM,MAAM;AAC1C,UAAA,CAAC,SAAiB,QAAA;AAClB,UAAA,MAAM,EAAE,IAAI,SAAS;AAClB,aAAA;AAAA,IACT;AAAA,IACA,CAAA;AAAA,EACF;AAEA,QAAM,OAAO,GAAG,YAAY,OAAO,EAAE,UAAU;AAE7C,eAAW,EAAE,WAAW,UAAU,KAAK,cAAc;AAE7C,YAAA,SAAS,UAAU,kBAAkB;AAE3C,YAAM,eAAe,UAAU,IAAI,CAAC,aAAa;AAC/C,cAAM,QAAQ,cAAc,SAAS,MAAM,CAAC;AAC5C,eAAO,EAAE,GAAG,UAAU,CAAC,MAAM,GAAG,MAAM;AAAA,MAAA,CACvC;AAGD,YAAM,IAAI,YAAY,UAAU,MAAM,cAAc,GAAI;AAAA,IAAA;AAAA,EAC1D,CACD;AACH;;;"}
|
@@ -44,8 +44,7 @@ const sync = async (oldEntries, newEntries, oldRelations) => {
|
|
44
44
|
const oldEntriesMap = oldEntries.reduce(
|
45
45
|
(acc, entry) => {
|
46
46
|
const newEntry = newEntryByLocale[entry.locale];
|
47
|
-
if (!newEntry)
|
48
|
-
return acc;
|
47
|
+
if (!newEntry) return acc;
|
49
48
|
acc[entry.id] = newEntry.id;
|
50
49
|
return acc;
|
51
50
|
},
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"unidirectional-relations.mjs","sources":["../../../../src/services/document-service/utils/unidirectional-relations.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport { keyBy, omit } from 'lodash/fp';\n\nimport { UID, Schema } from '@strapi/types';\n\ninterface LoadContext {\n oldVersions: { id: string; locale: string }[];\n newVersions: { id: string; locale: string }[];\n}\n\n/**\n * Loads lingering relations that need to be updated when overriding a published or draft entry.\n * This is necessary because the relations are uni-directional and the target entry is not aware of the source entry.\n * This is not the case for bi-directional relations, where the target entry is also linked to the source entry.\n */\nconst load = async (uid: UID.ContentType, { oldVersions, newVersions }: LoadContext) => {\n const updates = [] as any;\n\n // Iterate all components and content types to find relations that need to be updated\n await strapi.db.transaction(async ({ trx }) => {\n const contentTypes = Object.values(strapi.contentTypes) as Schema.ContentType[];\n const components = Object.values(strapi.components) as Schema.Component[];\n\n for (const model of [...contentTypes, ...components]) {\n const dbModel = strapi.db.metadata.get(model.uid);\n\n for (const attribute of Object.values(dbModel.attributes) as any) {\n /**\n * Only consider unidirectional relations\n */\n if (\n attribute.type !== 'relation' ||\n attribute.target !== uid ||\n attribute.inversedBy ||\n attribute.mappedBy\n ) {\n continue;\n }\n\n // TODO: joinColumn relations\n const joinTable = attribute.joinTable;\n if (!joinTable) {\n continue;\n }\n\n const { name: sourceColumnName } = joinTable.joinColumn;\n const { name: targetColumnName } = joinTable.inverseJoinColumn;\n\n /**\n * Load all relations that need to be updated\n */\n // NOTE: when the model has draft and publish, we can assume relation are only draft to draft & published to published\n const ids = oldVersions.map((entry) => entry.id);\n\n const oldVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (oldVersionsRelations.length > 0) {\n updates.push({ joinTable, relations: oldVersionsRelations });\n }\n\n /**\n * if publishing\n * if published version exists\n * updated published versions links\n * else\n * create link to newly published version\n *\n * if discarding\n * if published version link exists & not draft version link\n * create link to new draft version\n */\n\n if (!model.options?.draftAndPublish) {\n const ids = newVersions.map((entry) => entry.id);\n\n const newVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (newVersionsRelations.length > 0) {\n // when publishing a draft that doesn't have a published version yet,\n // copy the links to the draft over to the published version\n // when discarding a published version, if no drafts exists\n const discardToAdd = newVersionsRelations\n .filter((relation) => {\n const matchingOldVerion = oldVersionsRelations.find((oldRelation) => {\n return oldRelation[sourceColumnName] === relation[sourceColumnName];\n });\n\n return !matchingOldVerion;\n })\n .map(omit('id'));\n\n updates.push({ joinTable, relations: discardToAdd });\n }\n }\n }\n }\n });\n\n return updates;\n};\n\n/**\n * Updates uni directional relations to target the right entries when overriding published or draft entries.\n *\n * @param oldEntries The old entries that are being overridden\n * @param newEntries The new entries that are overriding the old ones\n * @param oldRelations The relations that were previously loaded with `load` @see load\n */\nconst sync = async (\n oldEntries: { id: string; locale: string }[],\n newEntries: { id: string; locale: string }[],\n oldRelations: { joinTable: any; relations: any[] }[]\n) => {\n /**\n * Create a map of old entry ids to new entry ids\n *\n * Will be used to update the relation target ids\n */\n const newEntryByLocale = keyBy('locale', newEntries);\n const oldEntriesMap = oldEntries.reduce(\n (acc, entry) => {\n const newEntry = newEntryByLocale[entry.locale];\n if (!newEntry) return acc;\n acc[entry.id] = newEntry.id;\n return acc;\n },\n {} as Record<string, string>\n );\n\n await strapi.db.transaction(async ({ trx }) => {\n // Iterate old relations that are deleted and insert the new ones\n for (const { joinTable, relations } of oldRelations) {\n // Update old ids with the new ones\n const column = joinTable.inverseJoinColumn.name;\n\n const newRelations = relations.map((relation) => {\n const newId = oldEntriesMap[relation[column]];\n return { ...relation, [column]: newId };\n });\n\n // Insert those relations into the join table\n await trx.batchInsert(joinTable.name, newRelations, 1000);\n }\n });\n};\n\nexport { load, sync };\n"],"names":["ids"],"mappings":";AAeA,MAAM,OAAO,OAAO,KAAsB,EAAE,aAAa,kBAA+B;AACtF,QAAM,UAAU,
|
1
|
+
{"version":3,"file":"unidirectional-relations.mjs","sources":["../../../../src/services/document-service/utils/unidirectional-relations.ts"],"sourcesContent":["/* eslint-disable no-continue */\nimport { keyBy, omit } from 'lodash/fp';\n\nimport { UID, Schema } from '@strapi/types';\n\ninterface LoadContext {\n oldVersions: { id: string; locale: string }[];\n newVersions: { id: string; locale: string }[];\n}\n\n/**\n * Loads lingering relations that need to be updated when overriding a published or draft entry.\n * This is necessary because the relations are uni-directional and the target entry is not aware of the source entry.\n * This is not the case for bi-directional relations, where the target entry is also linked to the source entry.\n */\nconst load = async (uid: UID.ContentType, { oldVersions, newVersions }: LoadContext) => {\n const updates = [] as any;\n\n // Iterate all components and content types to find relations that need to be updated\n await strapi.db.transaction(async ({ trx }) => {\n const contentTypes = Object.values(strapi.contentTypes) as Schema.ContentType[];\n const components = Object.values(strapi.components) as Schema.Component[];\n\n for (const model of [...contentTypes, ...components]) {\n const dbModel = strapi.db.metadata.get(model.uid);\n\n for (const attribute of Object.values(dbModel.attributes) as any) {\n /**\n * Only consider unidirectional relations\n */\n if (\n attribute.type !== 'relation' ||\n attribute.target !== uid ||\n attribute.inversedBy ||\n attribute.mappedBy\n ) {\n continue;\n }\n\n // TODO: joinColumn relations\n const joinTable = attribute.joinTable;\n if (!joinTable) {\n continue;\n }\n\n const { name: sourceColumnName } = joinTable.joinColumn;\n const { name: targetColumnName } = joinTable.inverseJoinColumn;\n\n /**\n * Load all relations that need to be updated\n */\n // NOTE: when the model has draft and publish, we can assume relation are only draft to draft & published to published\n const ids = oldVersions.map((entry) => entry.id);\n\n const oldVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (oldVersionsRelations.length > 0) {\n updates.push({ joinTable, relations: oldVersionsRelations });\n }\n\n /**\n * if publishing\n * if published version exists\n * updated published versions links\n * else\n * create link to newly published version\n *\n * if discarding\n * if published version link exists & not draft version link\n * create link to new draft version\n */\n\n if (!model.options?.draftAndPublish) {\n const ids = newVersions.map((entry) => entry.id);\n\n const newVersionsRelations = await strapi.db\n .getConnection()\n .select('*')\n .from(joinTable.name)\n .whereIn(targetColumnName, ids)\n .transacting(trx);\n\n if (newVersionsRelations.length > 0) {\n // when publishing a draft that doesn't have a published version yet,\n // copy the links to the draft over to the published version\n // when discarding a published version, if no drafts exists\n const discardToAdd = newVersionsRelations\n .filter((relation) => {\n const matchingOldVerion = oldVersionsRelations.find((oldRelation) => {\n return oldRelation[sourceColumnName] === relation[sourceColumnName];\n });\n\n return !matchingOldVerion;\n })\n .map(omit('id'));\n\n updates.push({ joinTable, relations: discardToAdd });\n }\n }\n }\n }\n });\n\n return updates;\n};\n\n/**\n * Updates uni directional relations to target the right entries when overriding published or draft entries.\n *\n * @param oldEntries The old entries that are being overridden\n * @param newEntries The new entries that are overriding the old ones\n * @param oldRelations The relations that were previously loaded with `load` @see load\n */\nconst sync = async (\n oldEntries: { id: string; locale: string }[],\n newEntries: { id: string; locale: string }[],\n oldRelations: { joinTable: any; relations: any[] }[]\n) => {\n /**\n * Create a map of old entry ids to new entry ids\n *\n * Will be used to update the relation target ids\n */\n const newEntryByLocale = keyBy('locale', newEntries);\n const oldEntriesMap = oldEntries.reduce(\n (acc, entry) => {\n const newEntry = newEntryByLocale[entry.locale];\n if (!newEntry) return acc;\n acc[entry.id] = newEntry.id;\n return acc;\n },\n {} as Record<string, string>\n );\n\n await strapi.db.transaction(async ({ trx }) => {\n // Iterate old relations that are deleted and insert the new ones\n for (const { joinTable, relations } of oldRelations) {\n // Update old ids with the new ones\n const column = joinTable.inverseJoinColumn.name;\n\n const newRelations = relations.map((relation) => {\n const newId = oldEntriesMap[relation[column]];\n return { ...relation, [column]: newId };\n });\n\n // Insert those relations into the join table\n await trx.batchInsert(joinTable.name, newRelations, 1000);\n }\n });\n};\n\nexport { load, sync };\n"],"names":["ids"],"mappings":";AAeA,MAAM,OAAO,OAAO,KAAsB,EAAE,aAAa,kBAA+B;AACtF,QAAM,UAAU,CAAC;AAGjB,QAAM,OAAO,GAAG,YAAY,OAAO,EAAE,UAAU;AAC7C,UAAM,eAAe,OAAO,OAAO,OAAO,YAAY;AACtD,UAAM,aAAa,OAAO,OAAO,OAAO,UAAU;AAElD,eAAW,SAAS,CAAC,GAAG,cAAc,GAAG,UAAU,GAAG;AACpD,YAAM,UAAU,OAAO,GAAG,SAAS,IAAI,MAAM,GAAG;AAEhD,iBAAW,aAAa,OAAO,OAAO,QAAQ,UAAU,GAAU;AAK9D,YAAA,UAAU,SAAS,cACnB,UAAU,WAAW,OACrB,UAAU,cACV,UAAU,UACV;AACA;AAAA,QAAA;AAIF,cAAM,YAAY,UAAU;AAC5B,YAAI,CAAC,WAAW;AACd;AAAA,QAAA;AAGF,cAAM,EAAE,MAAM,iBAAiB,IAAI,UAAU;AAC7C,cAAM,EAAE,MAAM,iBAAiB,IAAI,UAAU;AAM7C,cAAM,MAAM,YAAY,IAAI,CAAC,UAAU,MAAM,EAAE;AAE/C,cAAM,uBAAuB,MAAM,OAAO,GACvC,cAAc,EACd,OAAO,GAAG,EACV,KAAK,UAAU,IAAI,EACnB,QAAQ,kBAAkB,GAAG,EAC7B,YAAY,GAAG;AAEd,YAAA,qBAAqB,SAAS,GAAG;AACnC,kBAAQ,KAAK,EAAE,WAAW,WAAW,sBAAsB;AAAA,QAAA;AAezD,YAAA,CAAC,MAAM,SAAS,iBAAiB;AACnC,gBAAMA,OAAM,YAAY,IAAI,CAAC,UAAU,MAAM,EAAE;AAE/C,gBAAM,uBAAuB,MAAM,OAAO,GACvC,cAAc,EACd,OAAO,GAAG,EACV,KAAK,UAAU,IAAI,EACnB,QAAQ,kBAAkBA,IAAG,EAC7B,YAAY,GAAG;AAEd,cAAA,qBAAqB,SAAS,GAAG;AAInC,kBAAM,eAAe,qBAClB,OAAO,CAAC,aAAa;AACpB,oBAAM,oBAAoB,qBAAqB,KAAK,CAAC,gBAAgB;AACnE,uBAAO,YAAY,gBAAgB,MAAM,SAAS,gBAAgB;AAAA,cAAA,CACnE;AAED,qBAAO,CAAC;AAAA,YACT,CAAA,EACA,IAAI,KAAK,IAAI,CAAC;AAEjB,oBAAQ,KAAK,EAAE,WAAW,WAAW,cAAc;AAAA,UAAA;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF,CACD;AAEM,SAAA;AACT;AASA,MAAM,OAAO,OACX,YACA,YACA,iBACG;AAMG,QAAA,mBAAmB,MAAM,UAAU,UAAU;AACnD,QAAM,gBAAgB,WAAW;AAAA,IAC/B,CAAC,KAAK,UAAU;AACR,YAAA,WAAW,iBAAiB,MAAM,MAAM;AAC1C,UAAA,CAAC,SAAiB,QAAA;AAClB,UAAA,MAAM,EAAE,IAAI,SAAS;AAClB,aAAA;AAAA,IACT;AAAA,IACA,CAAA;AAAA,EACF;AAEA,QAAM,OAAO,GAAG,YAAY,OAAO,EAAE,UAAU;AAE7C,eAAW,EAAE,WAAW,UAAU,KAAK,cAAc;AAE7C,YAAA,SAAS,UAAU,kBAAkB;AAE3C,YAAM,eAAe,UAAU,IAAI,CAAC,aAAa;AAC/C,cAAM,QAAQ,cAAc,SAAS,MAAM,CAAC;AAC5C,eAAO,EAAE,GAAG,UAAU,CAAC,MAAM,GAAG,MAAM;AAAA,MAAA,CACvC;AAGD,YAAM,IAAI,YAAY,UAAU,MAAM,cAAc,GAAI;AAAA,IAAA;AAAA,EAC1D,CACD;AACH;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/services/entity-service/index.ts"],"sourcesContent":["import _ from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","_","relationUtils","delegate","errors"],"mappings":";;;;;;;;AA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AAS,SAAS,gBAAgB;AAG7C,SAAA,KAAK,QAAQ,cAAc,EAAE,QAAQ,CAAC,QAAQ,UAAU,OAAO,GAAG,CAAC;AAGlE,UAAA,SAAS,CAAC,eAAoD;AACpE,UAAM,aAAaF,WAAAA,QAAE;AAAA,MACnB;AAAA,MACA,CAAC,QAAQ,eACP,kBAA8D,MAAU;AAClE,YAAA;AACF,iBAAO,MAAO,WAAW,UAAU,EAAgC,KAAK,MAAM,GAAG,IAAI;AAAA,iBAC9E,OAAO;AACd,cACE,0BAA0B;AAAA,YACxB,CAAC,qBAAqB,iBAAiB;AAAA,UAAA,GAEzC;AACA,gBAAI,iBAAiB,OAAO;AAC1B,oBAAM,IAAIG,YAAAA,OAAO,gBAAgB,MAAM,OAAO;AAAA,YAChD;AAEM,kBAAA;AAAA,UACR;AACM,gBAAA;AAAA,QACR;AAAA,MACF;AAAA,IAAA;AAGG,WAAA;AAAA,EAAA,CACR;AAEM,SAAA;AACT;;"}
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/services/entity-service/index.ts"],"sourcesContent":["import _ from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","_","relationUtils","delegate","errors"],"mappings":";;;;;;;;AAmBA,MAAM,6BAA6B,CACjC,KACA,OACA,QACA,aAAa,CAAA,MACV;AACH,QAAM,QAAQ,OACX,IAAI,cAAc,EAClB,UAAU,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,GAAG,UAAiB;AAE1D,QAAM,MAAM;AAAA,IACV,GAAG,MAAM,SAAS,KAAK;AAAA,IACvB,GAAG;AAAA,EACL;AAEO,SAAA;AACT;AAEA,MAAM,4BAA4B;AAAA,EAChCA,SAAAA,OAAe;AAAA,EACfA,SAAAA,OAAe;AAAA,EACfA,SAAAA,OAAe;AAAA,EACfA,gBAAe;AACjB;AAEA,MAAM,8BAA8B,CAAC;AAAA,EACnC,QAAAC;AAAAA,EACA;AACF,OAG4C;AAAA,EAC1C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A,MACR;AAAA,IAEN;AAEO,WAAA;AAAA,EAAA,CACR;AAEM,SAAA;AACT;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-service/index.ts"],"sourcesContent":["import _ from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","relationUtils","errors"],"mappings":";;;;AAmBA,MAAM,6BAA6B,CACjC,KACA,OACA,QACA,aAAa,CAAA,MACV;AACH,QAAM,QAAQ,OACX,IAAI,cAAc,EAClB,UAAU,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,GAAG,OAAA,EAAiB,CAAA;AAE1D,QAAM,MAAM;AAAA,IACV,GAAG,MAAM,SAAS,KAAK;AAAA,IACvB,GAAG;AAAA,EAAA;AAGE,SAAA;AACT;AAEA,MAAM,4BAA4B;AAAA,EAChCA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AAAA,EACfA,OAAe;AACjB;AAEA,MAAM,8BAA8B,CAAC;AAAA,EACnC,QAAAC;AAAAA,EACA;AACF,OAG4C;AAAA,EAC1C,MAAM,WAAW,UAAe,IAAI;AAC3B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAc,IAAI;AAC1B,WAAA;AAAA,EACT;AAAA,EAEA,MAAM,SAAS,KAAK,MAAM;AACxB,UAAM,EAAE,KAASA,IAAAA,QAAO,SAAS,GAAG;AAE9B,UAAA,gBAAgB,MAAM,KAAK,WAAW,MAAM,EAAE,KAAK,QAAQ,WAAA,CAAY;AAE7E,QAAI,SAAS,cAAc;AACzB,YAAM,SAASA,QAAO,UAAW,GAAG,EAAE,UAAU,aAAa;AAC7D,aAAO,KAAK,WAAW,QAAQ,EAAE,KAAK,QAAQ,WAAW;AAAA,IAC3D;AAEA,UAAM,WAAW,MAAMA,QAAO,UAAW,GAAG,EAAE,SAAS,aAAa;AACpE,WAAO,KAAK,WAAW,UAAU,EAAE,KAAK,QAAQ,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AM,IAAI,MAAM,0CAA0C,OAAO,SAAS,EAAE;AAAA,MAC9E;AAEK,WAAA,iBAAiB,EAAE,GAAG,KAAK,gBAAgB,GAAG,UAAU,KAAK,cAAc;AACzE,aAAA;AAAA,IACT;AAAA,EAAA;AAGI,QAAA,YAAY,SAAS,SAAS,gBAAgB;AAG7C,SAAA,KAAK,QAAQ,cAAc,EAAE,QAAQ,CAAC,QAAQ,UAAU,OAAO,GAAG,CAAC;AAGlE,UAAA,SAAS,CAAC,eAAoD;AACpE,UAAM,aAAa,EAAE;AAAA,MACnB;AAAA,MACA,CAAC,QAAQ,eACP,kBAA8D,MAAU;AAClE,YAAA;AACF,iBAAO,MAAO,WAAW,UAAU,EAAgC,KAAK,MAAM,GAAG,IAAI;AAAA,iBAC9E,OAAO;AACd,cACE,0BAA0B;AAAA,YACxB,CAAC,qBAAqB,iBAAiB;AAAA,UAAA,GAEzC;AACA,gBAAI,iBAAiB,OAAO;AAC1B,oBAAM,IAAIC,SAAO,gBAAgB,MAAM,OAAO;AAAA,YAChD;AAEM,kBAAA;AAAA,UACR;AACM,gBAAA;AAAA,QACR;AAAA,MACF;AAAA,IAAA;AAGG,WAAA;AAAA,EAAA,CACR;AAEM,SAAA;AACT;"}
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-service/index.ts"],"sourcesContent":["import _ from 'lodash';\nimport delegate from 'delegates';\nimport { errors as databaseErrors } from '@strapi/database';\nimport {\n contentTypes as contentTypesUtils,\n errors,\n relations as relationUtils,\n} from '@strapi/utils';\nimport type { Database } from '@strapi/database';\nimport type { Core, Modules, Utils } from '@strapi/types';\n\ntype Decoratable<T> = T & {\n decorate(\n decorator: (old: Modules.EntityService.EntityService) => Modules.EntityService.EntityService & {\n [key: string]: unknown;\n }\n ): void;\n};\n\nconst transformLoadParamsToQuery = (\n uid: string,\n field: string,\n params: Record<string, unknown>,\n pagination = {}\n) => {\n const query = strapi\n .get('query-params')\n .transform(uid, { populate: { [field]: params } as any }) as any;\n\n const res = {\n ...query.populate[field],\n ...pagination,\n };\n\n return res;\n};\n\nconst databaseErrorsToTransform = [\n databaseErrors.InvalidTimeError,\n databaseErrors.InvalidDateTimeError,\n databaseErrors.InvalidDateError,\n databaseErrors.InvalidRelationError,\n];\n\nconst createDefaultImplementation = ({\n strapi,\n db,\n}: {\n strapi: Core.Strapi;\n db: Database;\n}): Modules.EntityService.EntityService => ({\n async wrapParams(options: any = {}) {\n return options;\n },\n\n async wrapResult(result: any = {}) {\n return result;\n },\n\n async findMany(uid, opts) {\n const { kind } = strapi.getModel(uid);\n\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findMany' });\n\n if (kind === 'singleType') {\n const entity = strapi.documents!(uid).findFirst(wrappedParams);\n return this.wrapResult(entity, { uid, action: 'findOne' });\n }\n\n const entities = await strapi.documents!(uid).findMany(wrappedParams);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findPage(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findPage' });\n\n const query = strapi.get('query-params').transform(uid, wrappedParams);\n\n const entities = await db.query(uid).findPage(query);\n return this.wrapResult(entities, { uid, action: 'findMany' });\n },\n\n async findOne(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'findOne' });\n\n const res = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!res) {\n return this.wrapResult(null, { uid, action: 'findOne' });\n }\n\n const entity = await strapi.documents!(uid).findOne({\n ...wrappedParams,\n documentId: res.documentId,\n });\n return this.wrapResult(entity, { uid, action: 'findOne' });\n },\n\n async count(uid, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'count' });\n\n return strapi.documents!(uid).count(wrappedParams);\n },\n\n async create(uid, params) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data' | 'fields' | 'populate'>\n >(params, { uid, action: 'create' });\n const { data } = wrappedParams;\n\n if (!data) {\n throw new Error('cannot create');\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(data, strapi.getModel(uid));\n\n const entity = await strapi.documents!(uid).create({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n });\n\n return this.wrapResult(entity, { uid, action: 'create' });\n },\n\n async update(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams<\n Modules.EntityService.Params.Pick<typeof uid, 'data:partial' | 'fields' | 'populate'>\n >(opts, {\n uid,\n action: 'update',\n });\n const entityToUpdate = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToUpdate) {\n return this.wrapResult(null, { uid, action: 'update' });\n }\n\n const shouldPublish = !contentTypesUtils.isDraft(entityToUpdate, strapi.getModel(uid));\n\n const entity = strapi.documents!(uid).update({\n ...(wrappedParams as any),\n status: shouldPublish ? 'published' : 'draft',\n documentId: entityToUpdate.documentId,\n });\n\n return this.wrapResult(entity, { uid, action: 'update' });\n },\n\n async delete(uid, entityId, opts) {\n const wrappedParams = await this.wrapParams(opts, { uid, action: 'delete' });\n\n const entityToDelete = await db.query(uid).findOne({ where: { id: entityId } });\n\n if (!entityToDelete) {\n return this.wrapResult(null, { uid, action: 'delete' });\n }\n\n await strapi.documents!(uid).delete({\n ...wrappedParams,\n documentId: entityToDelete.documentId,\n });\n\n return this.wrapResult(entityToDelete, { uid, action: 'delete' });\n },\n\n async load(uid, entity, field, params) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const loadedEntity = await db\n .query(uid)\n .load(entity, field, transformLoadParamsToQuery(uid, field, params ?? {}));\n\n return this.wrapResult(loadedEntity, { uid, field, action: 'load' });\n },\n\n async loadPages(uid, entity, field, params, pagination = {}) {\n if (!_.isString(field)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be a string`);\n }\n\n const { attributes } = strapi.getModel(uid);\n const attribute = attributes[field];\n\n if (!relationUtils.isAnyToMany(attribute)) {\n throw new Error(`Invalid load. Expected \"${field}\" to be an anyToMany relational attribute`);\n }\n\n const query = transformLoadParamsToQuery(uid, field, params ?? {}, pagination);\n\n const loadedPage = await db.query(uid).loadPages(entity, field, query);\n\n return {\n ...loadedPage,\n results: await this.wrapResult(loadedPage.results, { uid, field, action: 'load' }),\n };\n },\n});\n\nexport default (ctx: {\n strapi: Core.Strapi;\n db: Database;\n}): Decoratable<Modules.EntityService.EntityService> => {\n const implementation = createDefaultImplementation(ctx);\n\n const service = {\n implementation,\n decorate<T extends object>(decorator: (current: typeof implementation) => T) {\n if (typeof decorator !== 'function') {\n throw new Error(`Decorator must be a function, received ${typeof decorator}`);\n }\n\n this.implementation = { ...this.implementation, ...decorator(this.implementation) };\n return this;\n },\n };\n\n const delegator = delegate(service, 'implementation');\n\n // delegate every method in implementation\n Object.keys(service.implementation).forEach((key) => delegator.method(key));\n\n // wrap methods to handle Database Errors\n service.decorate((oldService: Modules.EntityService.EntityService) => {\n const newService = _.mapValues(\n oldService,\n (method, methodName: keyof Modules.EntityService.EntityService) =>\n async function (this: Modules.EntityService.EntityService, ...args: []) {\n try {\n return await (oldService[methodName] as Utils.Function.AnyPromise).call(this, ...args);\n } catch (error) {\n if (\n databaseErrorsToTransform.some(\n (errorToTransform) => error instanceof errorToTransform\n )\n ) {\n if (error instanceof Error) {\n throw new errors.ValidationError(error.message);\n }\n\n throw error;\n }\n throw error;\n }\n }\n );\n\n return newService;\n });\n\n return service as unknown as Decoratable<Modules.EntityService.EntityService>;\n};\n"],"names":["databaseErrors","strapi","contentTypesUtils","relationUtils","errors"],"mappings":";;;;AAmBA,MAAM,6BAA6B,CACjC,KACA,OACA,QACA,aAAa,CAAA,MACV;AACH,QAAM,QAAQ,OACX,IAAI,cAAc,EAClB,UAAU,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,GAAG,UAAiB;AAE1D,QAAM,MAAM;AAAA,IACV,GAAG,MAAM,SAAS,KAAK;AAAA,IACvB,GAAG;AAAA,EACL;AAEO,SAAA;AACT;AAEA,MAAM,4BAA4B;AAAA,EAChCA,OAAe;AAAA,EACfA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,OAAO;AAAA,YAAA;AAG1C,kBAAA;AAAA,UAAA;AAEF,gBAAA;AAAA,QAAA;AAAA,MACR;AAAA,IAEN;AAEO,WAAA;AAAA,EAAA,CACR;AAEM,SAAA;AACT;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"blocks-validator.js","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":["yup"],"mappings":";;;AAEA,MAAM,oBAAoBA,YAAA,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAMA,gBAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAMA,YAAAA,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,
|
1
|
+
{"version":3,"file":"blocks-validator.js","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":["yup"],"mappings":";;;AAEA,MAAM,oBAAoBA,YAAA,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAMA,gBAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAMA,YAAAA,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAAA;AAAA,EAEhD;AAAA,EACF,MAAMA,gBAAI,QAAQ;AAAA,EAClB,QAAQA,gBAAI,QAAQ;AAAA,EACpB,WAAWA,gBAAI,QAAQ;AAAA,EACvB,eAAeA,gBAAI,QAAQ;AAAA,EAC3B,MAAMA,gBAAI,QAAQ;AACpB,CAAC;AAED,MAAM,iBAAiB,CAAC,SAAiB;AACnC,MAAA;AAEE,QAAA,IAAI,KAAK,WAAW,GAAG,IAAI,oBAAoB,IAAI,KAAK,IAAI;AAAA,WACzD,OAAO;AACP,WAAA;AA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IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT,KAAK;AACI,aAAA;AAAA,IACT;AACE,aAAOA,YAAAA,IAAI,MAAM,EAAE,KAAK,gBAAgB,iCAAiC,MAAM;AACtE,eAAA;AAAA,MAAA,CACR;AAAA,EAAA;AAEP,CAAC;AAED,MAAM,wBAAwBA,YAAAA,IAAI,QAAQ,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"blocks-validator.mjs","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":[],"mappings":";AAEA,MAAM,oBAAoB,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAM,IAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAM,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,
|
1
|
+
{"version":3,"file":"blocks-validator.mjs","sources":["../../../src/services/entity-validator/blocks-validator.ts"],"sourcesContent":["import { yup } from '@strapi/utils';\n\nconst textNodeValidator = yup.object().shape({\n type: yup.string().equals(['text']).required(),\n text: yup\n .string()\n .test(\n 'is-valid-text',\n 'Text must be defined with at least an empty string',\n (text: unknown) => {\n return typeof text === 'string' || text === '';\n }\n ),\n bold: yup.boolean(),\n italic: yup.boolean(),\n underline: yup.boolean(),\n strikethrough: yup.boolean(),\n code: yup.boolean(),\n});\n\nconst checkValidLink = (link: string) => {\n try {\n // eslint-disable-next-line no-new\n new URL(link.startsWith('/') ? `https://strapi.io${link}` : link);\n } catch (error) {\n return false;\n }\n return true;\n};\n\nconst linkNodeValidator = yup.object().shape({\n type: yup.string().equals(['link']).required(),\n url: yup\n .string()\n .test('invalid-url', 'Please specify a valid link.', (value) => checkValidLink(value ?? '')),\n children: yup.array().of(textNodeValidator).required(),\n});\n\n// TODO: remove any with a correct Type\nconst inlineNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'text':\n return textNodeValidator;\n case 'link':\n return linkNodeValidator;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be Text or Link', () => {\n return false;\n });\n }\n});\n\nconst paragraphNodeValidator = yup.object().shape({\n type: yup.string().equals(['paragraph']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Paragraph node children must have at least one Text or Link node')\n .required(),\n});\n\nconst headingNodeValidator = yup.object().shape({\n type: yup.string().equals(['heading']).required(),\n level: yup.number().oneOf([1, 2, 3, 4, 5, 6]).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Heading node children must have at least one Text or Link node')\n .required(),\n});\n\nconst quoteNodeValidator = yup.object().shape({\n type: yup.string().equals(['quote']).required(),\n children: yup\n .array()\n .of(inlineNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst codeBlockValidator = yup.object().shape({\n type: yup.string().equals(['code']).required(),\n syntax: yup.string().nullable(),\n children: yup\n .array()\n .of(textNodeValidator)\n .min(1, 'Quote node children must have at least one Text or Link node')\n .required(),\n});\n\nconst listItemNode = yup.object().shape({\n type: yup.string().equals(['list-item']).required(),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// Allow children to be either a listItemNode or a listNode itself\n// @ts-expect-error - listChildrenValidator needs a type\nconst listChildrenValidator = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'list':\n return listNodeValidator;\n case 'list-item':\n return listItemNode;\n default:\n return yup.mixed().test('invalid-type', 'Inline node must be list-item or list', () => {\n return false;\n });\n }\n});\n\n// @ts-expect-error - listNodeValidator needs a type\nconst listNodeValidator = yup.object().shape({\n type: yup.string().equals(['list']).required(),\n format: yup.string().equals(['ordered', 'unordered']).required(),\n children: yup\n .array()\n .of(listChildrenValidator)\n .min(1, 'List node children must have at least one ListItem or ListNode')\n .required(),\n});\n\nconst imageNodeValidator = yup.object().shape({\n type: yup.string().equals(['image']).required(),\n image: yup.object().shape({\n name: yup.string().required(),\n alternativeText: yup.string().nullable(),\n url: yup.string().required(),\n caption: yup.string().nullable(),\n width: yup.number().required(),\n height: yup.number().required(),\n formats: yup.object().required(),\n hash: yup.string().required(),\n ext: yup.string().required(),\n mime: yup.string().required(),\n size: yup.number().required(),\n previewUrl: yup.string().nullable(),\n provider: yup.string().required(),\n provider_metadata: yup.mixed().nullable(),\n createdAt: yup.string().required(),\n updatedAt: yup.string().required(),\n }),\n children: yup.array().of(inlineNodeValidator).required(),\n});\n\n// TODO: remove the any and replace with a correct Type\nconst blockNodeValidator: any = yup.lazy((value: { type: string }) => {\n switch (value.type) {\n case 'paragraph':\n return paragraphNodeValidator;\n case 'heading':\n return headingNodeValidator;\n case 'quote':\n return quoteNodeValidator;\n case 'list':\n return listNodeValidator;\n case 'image':\n return imageNodeValidator;\n case 'code':\n return codeBlockValidator;\n default:\n return yup.mixed().test('invalid-type', 'Block node is of invalid type', () => {\n return false;\n });\n }\n});\n\nconst blocksValidatorSchema = yup.array().of(blockNodeValidator);\n\nexport const blocksValidator = () => blocksValidatorSchema;\n"],"names":[],"mappings":";AAEA,MAAM,oBAAoB,IAAI,OAAO,EAAE,MAAM;AAAA,EAC3C,MAAM,IAAI,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,EAC7C,MAAM,IACH,OAAA,EACA;AAAA,IACC;AAAA,IACA;AAAA,IACA,CAAC,SAAkB;AACV,aAAA,OAAO,SAAS,YAAY,SAAS;AAAA,IAAA;AAAA,EAEhD;AAAA,EACF,MAAM,IAAI,QAAQ;AAAA,EAClB,QAAQ,IAAI,QAAQ;AAAA,EACpB,WAAW,IAAI,QAAQ;AAAA,EACvB,eAAe,IAAI,QAAQ;AAAA,EAC3B,MAAM,IAAI,QAAQ;AACpB,CAAC;AAED,MAAM,iBAAiB,C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AA,EAAA;AAEP,CAAC;AAED,MAAM,wBAAwB,IAAI,QAAQ,GAAG,kBAAkB;AAExD,MAAM,kBAAkB,MAAM;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["strapiUtils","validator","prop","has","Validators","validators","isObject","data","isEmpty","isNil","castArray","mergeWith","isArray","value","uniqBy"],"mappings":";;;;;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0BA,qBAAAA,QAAY;AACnF,MAAM,EAAE,gBAAgB,IAAIA,qBAAY,QAAA;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;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,KAAK,KAAK,OAAO,QAAQ,cAAc,GAAG;AACzD,UAAM,WAAW,YAAY;AACrB,YAAA,eAAeE,EAAO,OAAA,OAAO,IAAI;AACvC,YAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,GAAiB,EAAE,MAAM;AAAA,QAC3D,OAAO;AAAA,UACL,IAAI;AAAA,YACF,KAAK,aAAa,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,CACD;AAEG,UAAA,UAAU,aAAa,QAAQ;AACjC,cAAM,IAAI;AAAA,UACR,GACE,aAAa,SAAS,KACxB,wBAAwB,GAAG;AAAA,QAAA;AAAA,MAE/B;AAAA,IAAA;AAEO,aAAA,KAAK,UAAU;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;;"}
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["strapiUtils","validator","prop","has","Validators","validators","isObject","data","isEmpty","isNil","castArray","mergeWith","isArray","value","uniqBy"],"mappings":";;;;;;;AAaA,MAAM,EAAE,KAAK,kBAAA,IAAsBA,qBAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,0BAA0BA,qBAAY,QAAA;AACnF,MAAM,EAAE,gBAAgB,IAAIA,qBAAAA,QAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAAA;AAExC,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAAA;AAErC,SAAA;AACT;AAEA,MAAM,wBAAwB,CAAC,mBAAmC;AAChE,SAAO,CACL,WACA;AAAA,IACE,MAAM,EAAE,SAAS;AAAA,EAAA,MAEb;AACN,QAAI,gBAAgB;AAEpB,QAAI,UAAU;AACZ,UAAI,mBAAmB,YAAY;AACjC,wBAAgB,cAAc,OAAO;AAAA,MAAA,WAC5B,mBAAmB,UAAU;AACtC,wBAAgB,cAAc,QAAQ;AAAA,MAAA;AAAA,IACxC,OACK;AACL,sBAAgB,cAAc,SAAS;AAAA,IAAA;AAElC,WAAA;AAAA,EACT;AACF;AAEA,MAAM,aAAa,CAAC,mBAAmC;AACrD,SAAO,CACL,WACA,EAAE,WACC;AACH,QAAI,gBAAgB;AAEpB,QAAI,mBAAmB,YAAY;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../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAA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xB,wBAAwB,GAAG;AAAA,QAAA;AAAA,MAE/B;AAAA,IAAA;AAEO,aAAA,KAAK,UAAU;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;"}
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAA,IAAsB;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,0BAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AAC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