@strapi/core 0.0.0-experimental.da85533897155e719d784f0271223c866d2f69ab → 0.0.0-experimental.de2b94258659463e5ddc5992e9a9490d66d950dd

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.
Files changed (81) hide show
  1. package/dist/core-api/service/collection-type.d.ts +2 -2
  2. package/dist/factories.js.map +1 -1
  3. package/dist/factories.mjs.map +1 -1
  4. package/dist/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
  5. package/dist/loaders/plugins/get-enabled-plugins.js +5 -2
  6. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  7. package/dist/loaders/plugins/get-enabled-plugins.mjs +5 -2
  8. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  9. package/dist/loaders/plugins/index.d.ts.map +1 -1
  10. package/dist/loaders/plugins/index.js +28 -1
  11. package/dist/loaders/plugins/index.js.map +1 -1
  12. package/dist/loaders/plugins/index.mjs +9 -1
  13. package/dist/loaders/plugins/index.mjs.map +1 -1
  14. package/dist/middlewares/security.d.ts.map +1 -1
  15. package/dist/middlewares/security.js +1 -1
  16. package/dist/middlewares/security.js.map +1 -1
  17. package/dist/middlewares/security.mjs +1 -1
  18. package/dist/middlewares/security.mjs.map +1 -1
  19. package/dist/migrations/database/5.0.0-discard-drafts.d.ts +12 -9
  20. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  21. package/dist/migrations/database/5.0.0-discard-drafts.js +55 -11
  22. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  23. package/dist/migrations/database/5.0.0-discard-drafts.mjs +56 -12
  24. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  25. package/dist/migrations/draft-publish.d.ts +1 -1
  26. package/dist/migrations/draft-publish.d.ts.map +1 -1
  27. package/dist/migrations/draft-publish.js.map +1 -1
  28. package/dist/migrations/draft-publish.mjs.map +1 -1
  29. package/dist/migrations/i18n.d.ts +5 -0
  30. package/dist/migrations/i18n.d.ts.map +1 -0
  31. package/dist/migrations/i18n.js +54 -0
  32. package/dist/migrations/i18n.js.map +1 -0
  33. package/dist/migrations/i18n.mjs +54 -0
  34. package/dist/migrations/i18n.mjs.map +1 -0
  35. package/dist/migrations/index.d.ts +5 -0
  36. package/dist/migrations/index.d.ts.map +1 -0
  37. package/dist/migrations/index.js +15 -0
  38. package/dist/migrations/index.js.map +1 -0
  39. package/dist/migrations/index.mjs +15 -0
  40. package/dist/migrations/index.mjs.map +1 -0
  41. package/dist/providers/admin.d.ts.map +1 -1
  42. package/dist/providers/admin.js.map +1 -1
  43. package/dist/providers/admin.mjs.map +1 -1
  44. package/dist/providers/registries.js +3 -3
  45. package/dist/providers/registries.js.map +1 -1
  46. package/dist/providers/registries.mjs +3 -3
  47. package/dist/providers/registries.mjs.map +1 -1
  48. package/dist/services/content-api/index.d.ts +6 -2
  49. package/dist/services/content-api/index.d.ts.map +1 -1
  50. package/dist/services/content-api/permissions/index.d.ts +6 -2
  51. package/dist/services/content-api/permissions/index.d.ts.map +1 -1
  52. package/dist/services/content-api/permissions/providers/action.d.ts +3 -1
  53. package/dist/services/content-api/permissions/providers/action.d.ts.map +1 -1
  54. package/dist/services/content-api/permissions/providers/condition.d.ts +3 -1
  55. package/dist/services/content-api/permissions/providers/condition.d.ts.map +1 -1
  56. package/dist/services/cron.d.ts +3 -3
  57. package/dist/services/cron.d.ts.map +1 -1
  58. package/dist/services/cron.js.map +1 -1
  59. package/dist/services/cron.mjs.map +1 -1
  60. package/dist/services/document-service/repository.d.ts.map +1 -1
  61. package/dist/services/document-service/repository.js +56 -6
  62. package/dist/services/document-service/repository.js.map +1 -1
  63. package/dist/services/document-service/repository.mjs +57 -7
  64. package/dist/services/document-service/repository.mjs.map +1 -1
  65. package/dist/services/document-service/utils/populate.d.ts.map +1 -1
  66. package/dist/services/document-service/utils/populate.js +3 -1
  67. package/dist/services/document-service/utils/populate.js.map +1 -1
  68. package/dist/services/document-service/utils/populate.mjs +3 -1
  69. package/dist/services/document-service/utils/populate.mjs.map +1 -1
  70. package/dist/services/document-service/utils/unidirectional-relations.d.ts +36 -0
  71. package/dist/services/document-service/utils/unidirectional-relations.d.ts.map +1 -0
  72. package/dist/services/document-service/utils/unidirectional-relations.js +67 -0
  73. package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -0
  74. package/dist/services/document-service/utils/unidirectional-relations.mjs +67 -0
  75. package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -0
  76. package/dist/services/entity-validator/index.d.ts.map +1 -1
  77. package/dist/services/entity-validator/index.js +6 -2
  78. package/dist/services/entity-validator/index.js.map +1 -1
  79. package/dist/services/entity-validator/index.mjs +6 -2
  80. package/dist/services/entity-validator/index.mjs.map +1 -1
  81. package/package.json +16 -15
@@ -1 +1 @@
1
- {"version":3,"file":"repository.mjs","sources":["../../../src/services/document-service/repository.ts"],"sourcesContent":["import { omit, assoc, merge, curry } from 'lodash/fp';\n\nimport { async, contentTypes as contentTypesUtils } from '@strapi/utils';\n\nimport { wrapInTransaction, type RepositoryFactoryMethod } from './common';\nimport * as DP from './draft-and-publish';\nimport * as i18n from './internationalization';\nimport * as components from './components';\n\nimport { createEntriesService } from './entries';\nimport { pickSelectionParams } from './params';\nimport { createDocumentId } from '../../utils/transform-content-types-to-models';\nimport { getDeepPopulate } from './utils/populate';\nimport { transformParamsToQuery } from './transform/query';\nimport { transformParamsDocumentId } from './transform/id-transform';\nimport { createEventManager } from './events';\n\nexport const createContentTypeRepository: RepositoryFactoryMethod = (uid) => {\n const contentType = strapi.contentType(uid);\n const hasDraftAndPublish = contentTypesUtils.hasDraftAndPublish(contentType);\n\n const entries = createEntriesService(uid);\n\n const eventManager = createEventManager(strapi, uid);\n const emitEvent = curry(eventManager.emitEvent);\n\n async function findMany(params = {} as any) {\n const query = await async.pipe(\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid)\n )(params || {});\n\n return strapi.db.query(uid).findMany(query);\n }\n\n async function findFirst(params = {} as any) {\n const query = await async.pipe(\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid)\n )(params);\n\n return strapi.db.query(uid).findOne(query);\n }\n\n // TODO: do we really want to add filters on the findOne now that we have findFirst ?\n async function findOne(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId }, query)\n )(params);\n\n return strapi.db.query(uid).findOne(query);\n }\n\n async function deleteDocument(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n omit('status'),\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId }, query)\n )(params);\n\n if (params.status === 'draft') {\n throw new Error('Cannot delete a draft document');\n }\n\n const entriesToDelete = await strapi.db.query(uid).findMany(query);\n\n // Delete all matched entries and its components\n const deletedEntries = await async.map(entriesToDelete, (entryToDelete: any) =>\n entries.delete(entryToDelete.id)\n );\n\n entriesToDelete.forEach(emitEvent('entry.delete'));\n\n return { documentId, entries: deletedEntries };\n }\n\n async function create(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n DP.filterDataPublishedAt,\n DP.setStatusToDraft(contentType),\n DP.statusToData(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToData(contentType)\n )(params);\n\n const doc = await entries.create(queryParams);\n\n emitEvent('entry.create', doc);\n\n if (hasDraftAndPublish && params.status === 'published') {\n return publish({\n ...params,\n documentId: doc.documentId,\n }).then((doc) => doc.entries[0]);\n }\n\n return doc;\n }\n\n async function clone(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n DP.filterDataPublishedAt,\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n // Get deep populate\n const entriesToClone = await strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n // DP Enabled: Clone drafts\n // DP Disabled: Clone only the existing version (published)\n publishedAt: { $null: hasDraftAndPublish },\n },\n populate: getDeepPopulate(uid, { relationalFields: ['id'] }),\n });\n\n const clonedEntries = await async.map(\n entriesToClone,\n async.pipe(\n omit('id'),\n // assign new documentId\n assoc('documentId', createDocumentId()),\n // Merge new data into it\n (data) => merge(data, queryParams.data),\n (data) => entries.create({ ...queryParams, data, status: 'draft' })\n )\n );\n\n clonedEntries.forEach(emitEvent('entry.create'));\n\n return { documentId: clonedEntries.at(0)?.documentId, entries: clonedEntries };\n }\n\n async function update(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n DP.filterDataPublishedAt,\n DP.setStatusToDraft(contentType),\n DP.statusToLookup(contentType),\n DP.statusToData(contentType),\n // Default locale will be set if not provided\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n i18n.localeToData(contentType)\n )(params);\n\n const { data, ...restParams } = await transformParamsDocumentId(uid, queryParams || {});\n const query = transformParamsToQuery(uid, pickSelectionParams(restParams || {}) as any);\n\n // Validation\n // Find if document exists\n const entryToUpdate = await strapi.db\n .query(uid)\n .findOne({ ...query, where: { ...queryParams?.lookup, ...query?.where, documentId } });\n\n let updatedDraft = null;\n if (entryToUpdate) {\n updatedDraft = await entries.update(entryToUpdate, queryParams);\n emitEvent('entry.update', updatedDraft);\n }\n\n if (!updatedDraft) {\n const documentExists = await strapi.db\n .query(contentType.uid)\n .findOne({ where: { documentId } });\n\n if (documentExists) {\n updatedDraft = await entries.create({\n ...queryParams,\n data: { ...queryParams.data, documentId },\n });\n emitEvent('entry.create', updatedDraft);\n }\n }\n\n if (hasDraftAndPublish && updatedDraft && params.status === 'published') {\n return publish({\n ...params,\n documentId,\n }).then((doc) => doc.entries[0]);\n }\n\n return updatedDraft;\n }\n\n async function count(params = {} as any) {\n const query = await async.pipe(\n DP.defaultStatus(contentType),\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsToQuery(uid)\n )(params);\n\n return strapi.db.query(uid).count(query);\n }\n\n async function publish(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n const [draftsToPublish, publishedToDelete] = await Promise.all([\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: null, // Ignore lookup\n },\n // Populate relations, media, compos and dz\n populate: getDeepPopulate(uid, { relationalFields: ['documentId', 'locale'] }),\n }),\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: { $ne: null },\n },\n select: ['id'],\n }),\n ]);\n\n // Delete all published versions\n await async.map(publishedToDelete, (entry: any) => entries.delete(entry.id));\n\n // Transform draft entry data and create published versions\n const publishedEntries = await async.map(draftsToPublish, (draft: unknown) =>\n entries.publish(draft, queryParams)\n );\n\n publishedEntries.forEach(emitEvent('entry.publish'));\n return { documentId, entries: publishedEntries };\n }\n\n async function unpublish(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId, publishedAt: { $ne: null } }, query)\n )(params);\n\n // Delete all published versions\n const versionsToDelete = await strapi.db.query(uid).findMany(query);\n await async.map(versionsToDelete, (entry: any) => entries.delete(entry.id));\n\n versionsToDelete.forEach(emitEvent('entry.unpublish'));\n return { documentId, entries: versionsToDelete };\n }\n\n async function discardDraft(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n const [versionsToDraft, versionsToDelete] = await Promise.all([\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: { $ne: null },\n },\n // Populate relations, media, compos and dz\n populate: getDeepPopulate(uid, { relationalFields: ['documentId', 'locale'] }),\n }),\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: null,\n },\n select: ['id'],\n }),\n ]);\n\n // Delete all drafts\n await async.map(versionsToDelete, (entry: any) => entries.delete(entry.id));\n\n // Transform published entry data and create draft versions\n const draftEntries = await async.map(versionsToDraft, (entry: any) =>\n entries.discardDraft(entry, queryParams)\n );\n\n draftEntries.forEach(emitEvent('entry.draft-discard'));\n return { documentId, entries: draftEntries };\n }\n\n async function updateComponents(entry: any, data: any) {\n return components.updateComponents(uid, entry, data);\n }\n\n function omitComponentData(data: any) {\n return components.omitComponentData(contentType, data);\n }\n\n return {\n findMany: wrapInTransaction(findMany),\n findFirst: wrapInTransaction(findFirst),\n findOne: wrapInTransaction(findOne),\n delete: wrapInTransaction(deleteDocument),\n create: wrapInTransaction(create),\n clone: wrapInTransaction(clone),\n update: wrapInTransaction(update),\n count: wrapInTransaction(count),\n publish: hasDraftAndPublish ? wrapInTransaction(publish) : (undefined as any),\n unpublish: hasDraftAndPublish ? wrapInTransaction(unpublish) : (undefined as any),\n discardDraft: hasDraftAndPublish ? wrapInTransaction(discardDraft) : (undefined as any),\n\n updateComponents,\n omitComponentData,\n };\n};\n"],"names":["contentTypesUtils","DP.defaultToDraft","DP.statusToLookup","i18n.defaultLocale","i18n.multiLocaleToLookup","transformParamsDocumentId","i18n.localeToLookup","query","DP.filterDataPublishedAt","DP.setStatusToDraft","DP.statusToData","i18n.localeToData","doc","DP.defaultStatus","updateComponents","components.updateComponents","omitComponentData","components.omitComponentData"],"mappings":";;;;;;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AAW;AAC7B,WAAAC,kBAA6B,aAAa,IAAI;AAAA,EACvD;AAEO,SAAA;AAAA,IACL,UAAU,kBAAkB,QAAQ;AAAA,IACpC,WAAW,kBAAkB,SAAS;AAAA,IACtC,SAAS,kBAAkB,OAAO;AAAA,IAClC,QAAQ,kBAAkB,cAAc;AAAA,IACxC,QAAQ,kBAAkB,MAAM;AAAA,IAChC,OAAO,kBAAkB,KAAK;AAAA,IAC9B,QAAQ,kBAAkB,MAAM;AAAA,IAChC,OAAO,kBAAkB,KAAK;AAAA,IAC9B,SAAS,qBAAqB,kBAAkB,OAAO,IAAK;AAAA,IAC5D,WAAW,qBAAqB,kBAAkB,SAAS,IAAK;AAAA,IAChE,cAAc,qBAAqB,kBAAkB,YAAY,IAAK;AAAA,IAAA,kBAEtEH;AAAAA,IAAA,mBACAE;AAAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"repository.mjs","sources":["../../../src/services/document-service/repository.ts"],"sourcesContent":["import { omit, assoc, merge, curry } from 'lodash/fp';\n\nimport { async, contentTypes as contentTypesUtils, validate } from '@strapi/utils';\n\nimport { UID } from '@strapi/types';\nimport { wrapInTransaction, type RepositoryFactoryMethod } from './common';\nimport * as DP from './draft-and-publish';\nimport * as i18n from './internationalization';\nimport * as components from './components';\n\nimport { createEntriesService } from './entries';\nimport { pickSelectionParams } from './params';\nimport { createDocumentId } from '../../utils/transform-content-types-to-models';\nimport { getDeepPopulate } from './utils/populate';\nimport { transformParamsToQuery } from './transform/query';\nimport { transformParamsDocumentId } from './transform/id-transform';\nimport { createEventManager } from './events';\nimport * as unidirectionalRelations from './utils/unidirectional-relations';\n\nconst { validators } = validate;\n\n// we have to typecast to reconcile the differences between validator and database getModel\nconst getModel = ((schema: UID.Schema) => strapi.getModel(schema)) as (schema: string) => any;\n\nexport const createContentTypeRepository: RepositoryFactoryMethod = (uid) => {\n const contentType = strapi.contentType(uid);\n const hasDraftAndPublish = contentTypesUtils.hasDraftAndPublish(contentType);\n\n // Define the validations that should be performed\n const sortValidations = ['nonAttributesOperators', 'dynamicZones', 'morphRelations'];\n const fieldValidations = ['scalarAttributes'];\n const filtersValidations = ['nonAttributesOperators', 'dynamicZones', 'morphRelations'];\n const populateValidations = {\n sort: sortValidations,\n field: fieldValidations,\n filters: filtersValidations,\n populate: ['nonAttributesOperators'],\n };\n\n const validateParams = async (params: any) => {\n const ctx = { schema: contentType, getModel };\n await validators.validateFilters(ctx, params.filters, filtersValidations);\n await validators.validateSort(ctx, params.sort, sortValidations);\n await validators.validateFields(ctx, params.fields, fieldValidations);\n await validators.validatePopulate(ctx, params.populate, populateValidations);\n\n // TODO: add validate status, locale, pagination\n\n return params;\n };\n\n const entries = createEntriesService(uid);\n\n const eventManager = createEventManager(strapi, uid);\n const emitEvent = curry(eventManager.emitEvent);\n\n async function findMany(params = {} as any) {\n const query = await async.pipe(\n validateParams,\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid)\n )(params || {});\n\n return strapi.db.query(uid).findMany(query);\n }\n\n async function findFirst(params = {} as any) {\n const query = await async.pipe(\n validateParams,\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid)\n )(params);\n\n return strapi.db.query(uid).findOne(query);\n }\n\n // TODO: do we really want to add filters on the findOne now that we have findFirst ?\n async function findOne(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n validateParams,\n DP.defaultToDraft,\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsDocumentId(uid),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId }, query)\n )(params);\n\n return strapi.db.query(uid).findOne(query);\n }\n\n async function deleteDocument(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n validateParams,\n omit('status'),\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId }, query)\n )(params);\n\n if (params.status === 'draft') {\n throw new Error('Cannot delete a draft document');\n }\n\n const entriesToDelete = await strapi.db.query(uid).findMany(query);\n\n // Delete all matched entries and its components\n const deletedEntries = await async.map(entriesToDelete, (entryToDelete: any) =>\n entries.delete(entryToDelete.id)\n );\n\n entriesToDelete.forEach(emitEvent('entry.delete'));\n\n return { documentId, entries: deletedEntries };\n }\n\n async function create(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n validateParams,\n DP.filterDataPublishedAt,\n DP.setStatusToDraft(contentType),\n DP.statusToData(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToData(contentType)\n )(params);\n\n const doc = await entries.create(queryParams);\n\n emitEvent('entry.create', doc);\n\n if (hasDraftAndPublish && params.status === 'published') {\n return publish({\n ...params,\n documentId: doc.documentId,\n }).then((doc) => doc.entries[0]);\n }\n\n return doc;\n }\n\n async function clone(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n validateParams,\n DP.filterDataPublishedAt,\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n // Get deep populate\n const entriesToClone = await strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n // DP Enabled: Clone drafts\n // DP Disabled: Clone only the existing version (published)\n publishedAt: { $null: hasDraftAndPublish },\n },\n populate: getDeepPopulate(uid, { relationalFields: ['id'] }),\n });\n\n const clonedEntries = await async.map(\n entriesToClone,\n async.pipe(\n validateParams,\n omit('id'),\n // assign new documentId\n assoc('documentId', createDocumentId()),\n // Merge new data into it\n (data) => merge(data, queryParams.data),\n (data) => entries.create({ ...queryParams, data, status: 'draft' })\n )\n );\n\n clonedEntries.forEach(emitEvent('entry.create'));\n\n return { documentId: clonedEntries.at(0)?.documentId, entries: clonedEntries };\n }\n\n async function update(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n validateParams,\n DP.filterDataPublishedAt,\n DP.setStatusToDraft(contentType),\n DP.statusToLookup(contentType),\n DP.statusToData(contentType),\n // Default locale will be set if not provided\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n i18n.localeToData(contentType)\n )(params);\n\n const { data, ...restParams } = await transformParamsDocumentId(uid, queryParams || {});\n const query = transformParamsToQuery(uid, pickSelectionParams(restParams || {}) as any);\n\n // Validation\n // Find if document exists\n const entryToUpdate = await strapi.db\n .query(uid)\n .findOne({ ...query, where: { ...queryParams?.lookup, ...query?.where, documentId } });\n\n let updatedDraft = null;\n if (entryToUpdate) {\n updatedDraft = await entries.update(entryToUpdate, queryParams);\n emitEvent('entry.update', updatedDraft);\n }\n\n if (!updatedDraft) {\n const documentExists = await strapi.db\n .query(contentType.uid)\n .findOne({ where: { documentId } });\n\n if (documentExists) {\n updatedDraft = await entries.create({\n ...queryParams,\n data: { ...queryParams.data, documentId },\n });\n emitEvent('entry.create', updatedDraft);\n }\n }\n\n if (hasDraftAndPublish && updatedDraft && params.status === 'published') {\n return publish({\n ...params,\n documentId,\n }).then((doc) => doc.entries[0]);\n }\n\n return updatedDraft;\n }\n\n async function count(params = {} as any) {\n const query = await async.pipe(\n validateParams,\n DP.defaultStatus(contentType),\n DP.statusToLookup(contentType),\n i18n.defaultLocale(contentType),\n i18n.localeToLookup(contentType),\n transformParamsToQuery(uid)\n )(params);\n\n return strapi.db.query(uid).count(query);\n }\n\n async function publish(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n validateParams,\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n const [draftsToPublish, oldPublishedVersions] = await Promise.all([\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: null, // Ignore lookup\n },\n // Populate relations, media, compos and dz\n populate: getDeepPopulate(uid, { relationalFields: ['documentId', 'locale'] }),\n }),\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: { $ne: null },\n },\n select: ['id', 'locale'],\n }),\n ]);\n\n // Load any unidirectional relation targetting the old published entries\n const relationsToSync = await unidirectionalRelations.load(uid, {\n newVersions: draftsToPublish,\n oldVersions: oldPublishedVersions,\n });\n\n // Delete old published versions\n await async.map(oldPublishedVersions, (entry: any) => entries.delete(entry.id));\n\n // Transform draft entry data and create published versions\n const publishedEntries = await async.map(draftsToPublish, (draft: any) =>\n entries.publish(draft, queryParams)\n );\n\n // Sync unidirectional relations with the new published entries\n await unidirectionalRelations.sync(\n [...oldPublishedVersions, ...draftsToPublish],\n publishedEntries,\n relationsToSync\n );\n\n publishedEntries.forEach(emitEvent('entry.publish'));\n\n return { documentId, entries: publishedEntries };\n }\n\n async function unpublish(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const query = await async.pipe(\n validateParams,\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType),\n transformParamsToQuery(uid),\n (query) => assoc('where', { ...query.where, documentId, publishedAt: { $ne: null } }, query)\n )(params);\n\n // Delete all published versions\n const versionsToDelete = await strapi.db.query(uid).findMany(query);\n await async.map(versionsToDelete, (entry: any) => entries.delete(entry.id));\n\n versionsToDelete.forEach(emitEvent('entry.unpublish'));\n return { documentId, entries: versionsToDelete };\n }\n\n async function discardDraft(opts = {} as any) {\n const { documentId, ...params } = opts;\n\n const queryParams = await async.pipe(\n validateParams,\n i18n.defaultLocale(contentType),\n i18n.multiLocaleToLookup(contentType)\n )(params);\n\n const [versionsToDraft, oldDrafts] = await Promise.all([\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: { $ne: null },\n },\n // Populate relations, media, compos and dz\n populate: getDeepPopulate(uid, { relationalFields: ['documentId', 'locale'] }),\n }),\n strapi.db.query(uid).findMany({\n where: {\n ...queryParams?.lookup,\n documentId,\n publishedAt: null,\n },\n select: ['id', 'locale'],\n }),\n ]);\n\n // Load any unidirectional relation targeting the old drafts\n const relationsToSync = await unidirectionalRelations.load(uid, {\n newVersions: versionsToDraft,\n oldVersions: oldDrafts,\n });\n\n // Delete old drafts\n await async.map(oldDrafts, (entry: any) => entries.delete(entry.id));\n\n // Transform published entry data and create draft versions\n const draftEntries = await async.map(versionsToDraft, (entry: any) =>\n entries.discardDraft(entry, queryParams)\n );\n\n // Sync unidirectional relations with the new draft entries\n await unidirectionalRelations.sync(\n [...oldDrafts, ...versionsToDraft],\n draftEntries,\n relationsToSync\n );\n\n draftEntries.forEach(emitEvent('entry.draft-discard'));\n return { documentId, entries: draftEntries };\n }\n\n async function updateComponents(entry: any, data: any) {\n return components.updateComponents(uid, entry, data);\n }\n\n function omitComponentData(data: any) {\n return components.omitComponentData(contentType, data);\n }\n\n return {\n findMany: wrapInTransaction(findMany),\n findFirst: wrapInTransaction(findFirst),\n findOne: wrapInTransaction(findOne),\n delete: wrapInTransaction(deleteDocument),\n create: wrapInTransaction(create),\n clone: wrapInTransaction(clone),\n update: wrapInTransaction(update),\n count: wrapInTransaction(count),\n publish: hasDraftAndPublish ? wrapInTransaction(publish) : (undefined as any),\n unpublish: hasDraftAndPublish ? wrapInTransaction(unpublish) : (undefined as any),\n discardDraft: hasDraftAndPublish ? wrapInTransaction(discardDraft) : (undefined as any),\n\n updateComponents,\n omitComponentData,\n };\n};\n"],"names":["contentTypesUtils","DP.defaultToDraft","DP.statusToLookup","i18n.defaultLocale","i18n.multiLocaleToLookup","transformParamsDocumentId","i18n.localeToLookup","query","DP.filterDataPublishedAt","DP.setStatusToDraft","DP.statusToData","i18n.localeToData","doc","DP.defaultStatus","unidirectionalRelations.load","unidirectionalRelations.sync","updateComponents","components.updateComponents","omitComponentData","components.omitComponentData"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAM,EAAE,WAAe,IAAA;AAGvB,MAAM,WAAY,CAAC,WAAu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,IACtC,SAAS,kBAAkB,OAAO;AAAA,IAClC,QAAQ,kBAAkB,cAAc;AAAA,IACxC,QAAQ,kBAAkB,MAAM;AAAA,IAChC,OAAO,kBAAkB,KAAK;AAAA,IAC9B,QAAQ,kBAAkB,MAAM;AAAA,IAChC,OAAO,kBAAkB,KAAK;AAAA,IAC9B,SAAS,qBAAqB,kBAAkB,OAAO,IAAK;AAAA,IAC5D,WAAW,qBAAqB,kBAAkB,SAAS,IAAK;AAAA,IAChE,cAAc,qBAAqB,kBAAkB,YAAY,IAAK;AAAA,IAAA,kBAEtEH;AAAAA,IAAA,mBACAE;AAAAA,EAAA;AAEJ;"}
@@ -1 +1 @@
1
- {"version":3,"file":"populate.d.ts","sourceRoot":"","sources":["../../../../src/services/document-service/utils/populate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAGpC,UAAU,OAAO;IACf;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAGD,eAAO,MAAM,eAAe,QAAS,IAAI,MAAM,SAAQ,OAAO,QAoD7D,CAAC"}
1
+ {"version":3,"file":"populate.d.ts","sourceRoot":"","sources":["../../../../src/services/document-service/utils/populate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AAGpC,UAAU,OAAO;IACf;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAKD,eAAO,MAAM,eAAe,QAAS,IAAI,MAAM,SAAQ,OAAO,QAsD7D,CAAC"}
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const strapiUtils = require("@strapi/utils");
4
+ const { CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = strapiUtils.contentTypes.constants;
4
5
  const getDeepPopulate = (uid, opts = {}) => {
5
6
  const model = strapi.getModel(uid);
6
7
  const attributes = Object.entries(model.attributes);
@@ -12,7 +13,8 @@ const getDeepPopulate = (uid, opts = {}) => {
12
13
  break;
13
14
  }
14
15
  const isVisible = strapiUtils.contentTypes.isVisibleAttribute(model, attributeName);
15
- if (isVisible) {
16
+ const isCreatorField = [CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE].includes(attributeName);
17
+ if (isVisible || isCreatorField) {
16
18
  acc[attributeName] = { select: opts.relationalFields };
17
19
  }
18
20
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"populate.js","sources":["../../../../src/services/document-service/utils/populate.ts"],"sourcesContent":["import { UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\ninterface Options {\n /**\n * Fields to select when populating relations\n */\n relationalFields?: string[];\n}\n\n// We want to build a populate object based on the schema\nexport const getDeepPopulate = (uid: UID.Schema, opts: Options = {}) => {\n const model = strapi.getModel(uid);\n const attributes = Object.entries(model.attributes);\n\n return attributes.reduce((acc: any, [attributeName, attribute]) => {\n switch (attribute.type) {\n case 'relation': {\n // TODO: Support polymorphic relations\n const isMorphRelation = attribute.relation.toLowerCase().startsWith('morph');\n if (isMorphRelation) {\n break;\n }\n\n // TODO: Should this just be a plain list?\n // Ignore createdBy, updatedBy, ...\n const isVisible = contentTypes.isVisibleAttribute(model, attributeName);\n if (isVisible) {\n acc[attributeName] = { select: opts.relationalFields };\n }\n break;\n }\n\n case 'media': {\n acc[attributeName] = { select: ['id'] };\n break;\n }\n\n case 'component': {\n const populate = getDeepPopulate(attribute.component, opts);\n acc[attributeName] = { populate };\n break;\n }\n\n case 'dynamiczone': {\n // Use fragments to populate the dynamic zone components\n const populatedComponents = (attribute.components || []).reduce(\n (acc: any, componentUID: UID.Component) => {\n acc[componentUID] = { populate: getDeepPopulate(componentUID, opts) };\n return acc;\n },\n {}\n );\n\n acc[attributeName] = { on: populatedComponents };\n break;\n }\n default:\n break;\n }\n\n return acc;\n }, {});\n};\n"],"names":["contentTypes","acc"],"mappings":";;;AAWO,MAAM,kBAAkB,CAAC,KAAiB,OAAgB,OAAO;AAChE,QAAA,QAAQ,OAAO,SAAS,GAAG;AACjC,QAAM,aAAa,OAAO,QAAQ,MAAM,UAAU;AAElD,SAAO,WAAW,OAAO,CAAC,KAAU,CAAC,eAAe,SAAS,MAAM;AACjE,YAAQ,UAAU,MAAM;AAAA,MACtB,KAAK,YAAY;AAEf,cAAM,kBAAkB,UAAU,SAAS,YAAY,EAAE,WAAW,OAAO;AAC3E,YAAI,iBAAiB;AACnB;AAAA,QACF;AAIA,cAAM,YAAYA,YAAA,aAAa,mBAAmB,OAAO,aAAa;AACtE,YAAI,WAAW;AACb,cAAI,aAAa,IAAI,EAAE,QAAQ,KAAK,iBAAiB;AAAA,QACvD;AACA;AAAA,MACF;AAAA,MAEA,KAAK,SAAS;AACZ,YAAI,aAAa,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;AACtC;AAAA,MACF;AAAA,MAEA,KAAK,aAAa;AAChB,cAAM,WAAW,gBAAgB,UAAU,WAAW,IAAI;AACtD,YAAA,aAAa,IAAI,EAAE;AACvB;AAAA,MACF;AAAA,MAEA,KAAK,eAAe;AAElB,cAAM,uBAAuB,UAAU,cAAc,CAAI,GAAA;AAAA,UACvD,CAACC,MAAU,iBAAgC;AACzCA,iBAAI,YAAY,IAAI,EAAE,UAAU,gBAAgB,cAAc,IAAI;AAC3DA,mBAAAA;AAAAA,UACT;AAAA,UACA,CAAC;AAAA,QAAA;AAGH,YAAI,aAAa,IAAI,EAAE,IAAI,oBAAoB;AAC/C;AAAA,MACF;AAAA,IAGF;AAEO,WAAA;AAAA,EACT,GAAG,CAAE,CAAA;AACP;;"}
1
+ {"version":3,"file":"populate.js","sources":["../../../../src/services/document-service/utils/populate.ts"],"sourcesContent":["import { UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\ninterface Options {\n /**\n * Fields to select when populating relations\n */\n relationalFields?: string[];\n}\n\nconst { CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = contentTypes.constants;\n\n// We want to build a populate object based on the schema\nexport const getDeepPopulate = (uid: UID.Schema, opts: Options = {}) => {\n const model = strapi.getModel(uid);\n const attributes = Object.entries(model.attributes);\n\n return attributes.reduce((acc: any, [attributeName, attribute]) => {\n switch (attribute.type) {\n case 'relation': {\n // TODO: Support polymorphic relations\n const isMorphRelation = attribute.relation.toLowerCase().startsWith('morph');\n if (isMorphRelation) {\n break;\n }\n\n // Ignore not visible fields other than createdBy and updatedBy\n const isVisible = contentTypes.isVisibleAttribute(model, attributeName);\n const isCreatorField = [CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE].includes(attributeName);\n\n if (isVisible || isCreatorField) {\n acc[attributeName] = { select: opts.relationalFields };\n }\n\n break;\n }\n\n case 'media': {\n acc[attributeName] = { select: ['id'] };\n break;\n }\n\n case 'component': {\n const populate = getDeepPopulate(attribute.component, opts);\n acc[attributeName] = { populate };\n break;\n }\n\n case 'dynamiczone': {\n // Use fragments to populate the dynamic zone components\n const populatedComponents = (attribute.components || []).reduce(\n (acc: any, componentUID: UID.Component) => {\n acc[componentUID] = { populate: getDeepPopulate(componentUID, opts) };\n return acc;\n },\n {}\n );\n\n acc[attributeName] = { on: populatedComponents };\n break;\n }\n default:\n break;\n }\n\n return acc;\n }, {});\n};\n"],"names":["contentTypes","acc"],"mappings":";;;AAUA,MAAM,EAAE,sBAAsB,yBAAyBA,YAAAA,aAAa;AAG7D,MAAM,kBAAkB,CAAC,KAAiB,OAAgB,OAAO;AAChE,QAAA,QAAQ,OAAO,SAAS,GAAG;AACjC,QAAM,aAAa,OAAO,QAAQ,MAAM,UAAU;AAElD,SAAO,WAAW,OAAO,CAAC,KAAU,CAAC,eAAe,SAAS,MAAM;AACjE,YAAQ,UAAU,MAAM;AAAA,MACtB,KAAK,YAAY;AAEf,cAAM,kBAAkB,UAAU,SAAS,YAAY,EAAE,WAAW,OAAO;AAC3E,YAAI,iBAAiB;AACnB;AAAA,QACF;AAGA,cAAM,YAAYA,YAAA,aAAa,mBAAmB,OAAO,aAAa;AACtE,cAAM,iBAAiB,CAAC,sBAAsB,oBAAoB,EAAE,SAAS,aAAa;AAE1F,YAAI,aAAa,gBAAgB;AAC/B,cAAI,aAAa,IAAI,EAAE,QAAQ,KAAK,iBAAiB;AAAA,QACvD;AAEA;AAAA,MACF;AAAA,MAEA,KAAK,SAAS;AACZ,YAAI,aAAa,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;AACtC;AAAA,MACF;AAAA,MAEA,KAAK,aAAa;AAChB,cAAM,WAAW,gBAAgB,UAAU,WAAW,IAAI;AACtD,YAAA,aAAa,IAAI,EAAE;AACvB;AAAA,MACF;AAAA,MAEA,KAAK,eAAe;AAElB,cAAM,uBAAuB,UAAU,cAAc,CAAI,GAAA;AAAA,UACvD,CAACC,MAAU,iBAAgC;AACzCA,iBAAI,YAAY,IAAI,EAAE,UAAU,gBAAgB,cAAc,IAAI;AAC3DA,mBAAAA;AAAAA,UACT;AAAA,UACA,CAAC;AAAA,QAAA;AAGH,YAAI,aAAa,IAAI,EAAE,IAAI,oBAAoB;AAC/C;AAAA,MACF;AAAA,IAGF;AAEO,WAAA;AAAA,EACT,GAAG,CAAE,CAAA;AACP;;"}
@@ -1,4 +1,5 @@
1
1
  import { contentTypes } from "@strapi/utils";
2
+ const { CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = contentTypes.constants;
2
3
  const getDeepPopulate = (uid, opts = {}) => {
3
4
  const model = strapi.getModel(uid);
4
5
  const attributes = Object.entries(model.attributes);
@@ -10,7 +11,8 @@ const getDeepPopulate = (uid, opts = {}) => {
10
11
  break;
11
12
  }
12
13
  const isVisible = contentTypes.isVisibleAttribute(model, attributeName);
13
- if (isVisible) {
14
+ const isCreatorField = [CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE].includes(attributeName);
15
+ if (isVisible || isCreatorField) {
14
16
  acc[attributeName] = { select: opts.relationalFields };
15
17
  }
16
18
  break;
@@ -1 +1 @@
1
- {"version":3,"file":"populate.mjs","sources":["../../../../src/services/document-service/utils/populate.ts"],"sourcesContent":["import { UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\ninterface Options {\n /**\n * Fields to select when populating relations\n */\n relationalFields?: string[];\n}\n\n// We want to build a populate object based on the schema\nexport const getDeepPopulate = (uid: UID.Schema, opts: Options = {}) => {\n const model = strapi.getModel(uid);\n const attributes = Object.entries(model.attributes);\n\n return attributes.reduce((acc: any, [attributeName, attribute]) => {\n switch (attribute.type) {\n case 'relation': {\n // TODO: Support polymorphic relations\n const isMorphRelation = attribute.relation.toLowerCase().startsWith('morph');\n if (isMorphRelation) {\n break;\n }\n\n // TODO: Should this just be a plain list?\n // Ignore createdBy, updatedBy, ...\n const isVisible = contentTypes.isVisibleAttribute(model, attributeName);\n if (isVisible) {\n acc[attributeName] = { select: opts.relationalFields };\n }\n break;\n }\n\n case 'media': {\n acc[attributeName] = { select: ['id'] };\n break;\n }\n\n case 'component': {\n const populate = getDeepPopulate(attribute.component, opts);\n acc[attributeName] = { populate };\n break;\n }\n\n case 'dynamiczone': {\n // Use fragments to populate the dynamic zone components\n const populatedComponents = (attribute.components || []).reduce(\n (acc: any, componentUID: UID.Component) => {\n acc[componentUID] = { populate: getDeepPopulate(componentUID, opts) };\n return acc;\n },\n {}\n );\n\n acc[attributeName] = { on: populatedComponents };\n break;\n }\n default:\n break;\n }\n\n return acc;\n }, {});\n};\n"],"names":["acc"],"mappings":";AAWO,MAAM,kBAAkB,CAAC,KAAiB,OAAgB,OAAO;AAChE,QAAA,QAAQ,OAAO,SAAS,GAAG;AACjC,QAAM,aAAa,OAAO,QAAQ,MAAM,UAAU;AAElD,SAAO,WAAW,OAAO,CAAC,KAAU,CAAC,eAAe,SAAS,MAAM;AACjE,YAAQ,UAAU,MAAM;AAAA,MACtB,KAAK,YAAY;AAEf,cAAM,kBAAkB,UAAU,SAAS,YAAY,EAAE,WAAW,OAAO;AAC3E,YAAI,iBAAiB;AACnB;AAAA,QACF;AAIA,cAAM,YAAY,aAAa,mBAAmB,OAAO,aAAa;AACtE,YAAI,WAAW;AACb,cAAI,aAAa,IAAI,EAAE,QAAQ,KAAK,iBAAiB;AAAA,QACvD;AACA;AAAA,MACF;AAAA,MAEA,KAAK,SAAS;AACZ,YAAI,aAAa,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;AACtC;AAAA,MACF;AAAA,MAEA,KAAK,aAAa;AAChB,cAAM,WAAW,gBAAgB,UAAU,WAAW,IAAI;AACtD,YAAA,aAAa,IAAI,EAAE;AACvB;AAAA,MACF;AAAA,MAEA,KAAK,eAAe;AAElB,cAAM,uBAAuB,UAAU,cAAc,CAAI,GAAA;AAAA,UACvD,CAACA,MAAU,iBAAgC;AACzCA,iBAAI,YAAY,IAAI,EAAE,UAAU,gBAAgB,cAAc,IAAI;AAC3DA,mBAAAA;AAAAA,UACT;AAAA,UACA,CAAC;AAAA,QAAA;AAGH,YAAI,aAAa,IAAI,EAAE,IAAI,oBAAoB;AAC/C;AAAA,MACF;AAAA,IAGF;AAEO,WAAA;AAAA,EACT,GAAG,CAAE,CAAA;AACP;"}
1
+ {"version":3,"file":"populate.mjs","sources":["../../../../src/services/document-service/utils/populate.ts"],"sourcesContent":["import { UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\ninterface Options {\n /**\n * Fields to select when populating relations\n */\n relationalFields?: string[];\n}\n\nconst { CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = contentTypes.constants;\n\n// We want to build a populate object based on the schema\nexport const getDeepPopulate = (uid: UID.Schema, opts: Options = {}) => {\n const model = strapi.getModel(uid);\n const attributes = Object.entries(model.attributes);\n\n return attributes.reduce((acc: any, [attributeName, attribute]) => {\n switch (attribute.type) {\n case 'relation': {\n // TODO: Support polymorphic relations\n const isMorphRelation = attribute.relation.toLowerCase().startsWith('morph');\n if (isMorphRelation) {\n break;\n }\n\n // Ignore not visible fields other than createdBy and updatedBy\n const isVisible = contentTypes.isVisibleAttribute(model, attributeName);\n const isCreatorField = [CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE].includes(attributeName);\n\n if (isVisible || isCreatorField) {\n acc[attributeName] = { select: opts.relationalFields };\n }\n\n break;\n }\n\n case 'media': {\n acc[attributeName] = { select: ['id'] };\n break;\n }\n\n case 'component': {\n const populate = getDeepPopulate(attribute.component, opts);\n acc[attributeName] = { populate };\n break;\n }\n\n case 'dynamiczone': {\n // Use fragments to populate the dynamic zone components\n const populatedComponents = (attribute.components || []).reduce(\n (acc: any, componentUID: UID.Component) => {\n acc[componentUID] = { populate: getDeepPopulate(componentUID, opts) };\n return acc;\n },\n {}\n );\n\n acc[attributeName] = { on: populatedComponents };\n break;\n }\n default:\n break;\n }\n\n return acc;\n }, {});\n};\n"],"names":["acc"],"mappings":";AAUA,MAAM,EAAE,sBAAsB,yBAAyB,aAAa;AAG7D,MAAM,kBAAkB,CAAC,KAAiB,OAAgB,OAAO;AAChE,QAAA,QAAQ,OAAO,SAAS,GAAG;AACjC,QAAM,aAAa,OAAO,QAAQ,MAAM,UAAU;AAElD,SAAO,WAAW,OAAO,CAAC,KAAU,CAAC,eAAe,SAAS,MAAM;AACjE,YAAQ,UAAU,MAAM;AAAA,MACtB,KAAK,YAAY;AAEf,cAAM,kBAAkB,UAAU,SAAS,YAAY,EAAE,WAAW,OAAO;AAC3E,YAAI,iBAAiB;AACnB;AAAA,QACF;AAGA,cAAM,YAAY,aAAa,mBAAmB,OAAO,aAAa;AACtE,cAAM,iBAAiB,CAAC,sBAAsB,oBAAoB,EAAE,SAAS,aAAa;AAE1F,YAAI,aAAa,gBAAgB;AAC/B,cAAI,aAAa,IAAI,EAAE,QAAQ,KAAK,iBAAiB;AAAA,QACvD;AAEA;AAAA,MACF;AAAA,MAEA,KAAK,SAAS;AACZ,YAAI,aAAa,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE;AACtC;AAAA,MACF;AAAA,MAEA,KAAK,aAAa;AAChB,cAAM,WAAW,gBAAgB,UAAU,WAAW,IAAI;AACtD,YAAA,aAAa,IAAI,EAAE;AACvB;AAAA,MACF;AAAA,MAEA,KAAK,eAAe;AAElB,cAAM,uBAAuB,UAAU,cAAc,CAAI,GAAA;AAAA,UACvD,CAACA,MAAU,iBAAgC;AACzCA,iBAAI,YAAY,IAAI,EAAE,UAAU,gBAAgB,cAAc,IAAI;AAC3DA,mBAAAA;AAAAA,UACT;AAAA,UACA,CAAC;AAAA,QAAA;AAGH,YAAI,aAAa,IAAI,EAAE,IAAI,oBAAoB;AAC/C;AAAA,MACF;AAAA,IAGF;AAEO,WAAA;AAAA,EACT,GAAG,CAAE,CAAA;AACP;"}
@@ -0,0 +1,36 @@
1
+ import { UID } from '@strapi/types';
2
+ interface LoadContext {
3
+ oldVersions: {
4
+ id: string;
5
+ locale: string;
6
+ }[];
7
+ newVersions: {
8
+ id: string;
9
+ locale: string;
10
+ }[];
11
+ }
12
+ /**
13
+ * Loads lingering relations that need to be updated when overriding a published or draft entry.
14
+ * This is necessary because the relations are uni-directional and the target entry is not aware of the source entry.
15
+ * This is not the case for bi-directional relations, where the target entry is also linked to the source entry.
16
+ */
17
+ declare const load: (uid: UID.ContentType, { oldVersions, newVersions }: LoadContext) => Promise<any>;
18
+ /**
19
+ * Updates uni directional relations to target the right entries when overriding published or draft entries.
20
+ *
21
+ * @param oldEntries The old entries that are being overridden
22
+ * @param newEntries The new entries that are overriding the old ones
23
+ * @param oldRelations The relations that were previously loaded with `load` @see load
24
+ */
25
+ declare const sync: (oldEntries: {
26
+ id: string;
27
+ locale: string;
28
+ }[], newEntries: {
29
+ id: string;
30
+ locale: string;
31
+ }[], oldRelations: {
32
+ joinTable: any;
33
+ relations: any[];
34
+ }[]) => Promise<void>;
35
+ export { load, sync };
36
+ //# sourceMappingURL=unidirectional-relations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unidirectional-relations.d.ts","sourceRoot":"","sources":["../../../../src/services/document-service/utils/unidirectional-relations.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,GAAG,EAAU,MAAM,eAAe,CAAC;AAE5C,UAAU,WAAW;IACnB,WAAW,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,WAAW,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CAC/C;AAED;;;;GAIG;AACH,QAAA,MAAM,IAAI,QAAe,IAAI,WAAW,gCAAgC,WAAW,iBA4FlF,CAAC;AAEF;;;;;;GAMG;AACH,QAAA,MAAM,IAAI,eACI;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,cAChC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,gBAC9B;IAAE,SAAS,EAAE,GAAG,CAAC;IAAC,SAAS,EAAE,GAAG,EAAE,CAAA;CAAE,EAAE,kBAiCrD,CAAC;AAEF,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC"}
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const fp = require("lodash/fp");
4
+ const load = async (uid, { oldVersions, newVersions }) => {
5
+ const updates = [];
6
+ await strapi.db.transaction(async ({ trx }) => {
7
+ const contentTypes = Object.values(strapi.contentTypes);
8
+ const components = Object.values(strapi.components);
9
+ for (const model of [...contentTypes, ...components]) {
10
+ const dbModel = strapi.db.metadata.get(model.uid);
11
+ for (const attribute of Object.values(dbModel.attributes)) {
12
+ if (attribute.type !== "relation" || attribute.target !== uid || attribute.inversedBy || attribute.mappedBy) {
13
+ continue;
14
+ }
15
+ const joinTable = attribute.joinTable;
16
+ if (!joinTable) {
17
+ continue;
18
+ }
19
+ const { name } = joinTable.inverseJoinColumn;
20
+ const ids = oldVersions.map((entry) => entry.id);
21
+ const oldVersionsRelations = await strapi.db.getConnection().select("*").from(joinTable.name).whereIn(name, ids).transacting(trx);
22
+ if (oldVersionsRelations.length > 0) {
23
+ updates.push({ joinTable, relations: oldVersionsRelations });
24
+ }
25
+ if (!model.options?.draftAndPublish) {
26
+ const ids2 = newVersions.map((entry) => entry.id);
27
+ const newVersionsRelations = await strapi.db.getConnection().select("*").from(joinTable.name).whereIn(name, ids2).transacting(trx);
28
+ if (newVersionsRelations.length > 0) {
29
+ const discardToAdd = newVersionsRelations.filter((relation) => {
30
+ return !oldVersionsRelations.find((oldRelation) => {
31
+ return oldRelation[name] === relation[name];
32
+ });
33
+ }).filter(Boolean).map(fp.omit("id"));
34
+ updates.push({ joinTable, relations: discardToAdd });
35
+ }
36
+ }
37
+ }
38
+ }
39
+ });
40
+ return updates;
41
+ };
42
+ const sync = async (oldEntries, newEntries, oldRelations) => {
43
+ const newEntryByLocale = fp.keyBy("locale", newEntries);
44
+ const oldEntriesMap = oldEntries.reduce(
45
+ (acc, entry) => {
46
+ const newEntry = newEntryByLocale[entry.locale];
47
+ if (!newEntry)
48
+ return acc;
49
+ acc[entry.id] = newEntry.id;
50
+ return acc;
51
+ },
52
+ {}
53
+ );
54
+ await strapi.db.transaction(async ({ trx }) => {
55
+ for (const { joinTable, relations } of oldRelations) {
56
+ const column = joinTable.inverseJoinColumn.name;
57
+ const newRelations = relations.map((relation) => {
58
+ const newId = oldEntriesMap[relation[column]];
59
+ return { ...relation, [column]: newId };
60
+ });
61
+ await trx.insert(newRelations).into(joinTable.name).onConflict().ignore();
62
+ }
63
+ });
64
+ };
65
+ exports.load = load;
66
+ exports.sync = sync;
67
+ //# sourceMappingURL=unidirectional-relations.js.map
@@ -0,0 +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 } = 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(name, 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(name, 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 return !oldVersionsRelations.find((oldRelation) => {\n return oldRelation[name] === relation[name];\n });\n })\n .filter(Boolean)\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.insert(newRelations).into(joinTable.name).onConflict().ignore();\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,CAAA;AAGhB,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,YA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AAAA,MAAM,UAAU,UAAU;AACnD,QAAM,gBAAgB,WAAW;AAAA,IAC/B,CAAC,KAAK,UAAU;AACR,YAAA,WAAW,iBAAiB,MAAM,MAAM;AAC9C,UAAI,CAAC;AAAiB,eAAA;AAClB,UAAA,MAAM,EAAE,IAAI,SAAS;AAClB,aAAA;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EAAA;AAGH,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;AAGK,YAAA,IAAI,OAAO,YAAY,EAAE,KAAK,UAAU,IAAI,EAAE,aAAa;IACnE;AAAA,EAAA,CACD;AACH;;;"}
@@ -0,0 +1,67 @@
1
+ import { omit, keyBy } from "lodash/fp";
2
+ const load = async (uid, { oldVersions, newVersions }) => {
3
+ const updates = [];
4
+ await strapi.db.transaction(async ({ trx }) => {
5
+ const contentTypes = Object.values(strapi.contentTypes);
6
+ const components = Object.values(strapi.components);
7
+ for (const model of [...contentTypes, ...components]) {
8
+ const dbModel = strapi.db.metadata.get(model.uid);
9
+ for (const attribute of Object.values(dbModel.attributes)) {
10
+ if (attribute.type !== "relation" || attribute.target !== uid || attribute.inversedBy || attribute.mappedBy) {
11
+ continue;
12
+ }
13
+ const joinTable = attribute.joinTable;
14
+ if (!joinTable) {
15
+ continue;
16
+ }
17
+ const { name } = joinTable.inverseJoinColumn;
18
+ const ids = oldVersions.map((entry) => entry.id);
19
+ const oldVersionsRelations = await strapi.db.getConnection().select("*").from(joinTable.name).whereIn(name, ids).transacting(trx);
20
+ if (oldVersionsRelations.length > 0) {
21
+ updates.push({ joinTable, relations: oldVersionsRelations });
22
+ }
23
+ if (!model.options?.draftAndPublish) {
24
+ const ids2 = newVersions.map((entry) => entry.id);
25
+ const newVersionsRelations = await strapi.db.getConnection().select("*").from(joinTable.name).whereIn(name, ids2).transacting(trx);
26
+ if (newVersionsRelations.length > 0) {
27
+ const discardToAdd = newVersionsRelations.filter((relation) => {
28
+ return !oldVersionsRelations.find((oldRelation) => {
29
+ return oldRelation[name] === relation[name];
30
+ });
31
+ }).filter(Boolean).map(omit("id"));
32
+ updates.push({ joinTable, relations: discardToAdd });
33
+ }
34
+ }
35
+ }
36
+ }
37
+ });
38
+ return updates;
39
+ };
40
+ const sync = async (oldEntries, newEntries, oldRelations) => {
41
+ const newEntryByLocale = keyBy("locale", newEntries);
42
+ const oldEntriesMap = oldEntries.reduce(
43
+ (acc, entry) => {
44
+ const newEntry = newEntryByLocale[entry.locale];
45
+ if (!newEntry)
46
+ return acc;
47
+ acc[entry.id] = newEntry.id;
48
+ return acc;
49
+ },
50
+ {}
51
+ );
52
+ await strapi.db.transaction(async ({ trx }) => {
53
+ for (const { joinTable, relations } of oldRelations) {
54
+ const column = joinTable.inverseJoinColumn.name;
55
+ const newRelations = relations.map((relation) => {
56
+ const newId = oldEntriesMap[relation[column]];
57
+ return { ...relation, [column]: newId };
58
+ });
59
+ await trx.insert(newRelations).into(joinTable.name).onConflict().ignore();
60
+ }
61
+ });
62
+ };
63
+ export {
64
+ load,
65
+ sync
66
+ };
67
+ //# sourceMappingURL=unidirectional-relations.mjs.map
@@ -0,0 +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 } = 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(name, 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(name, 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 return !oldVersionsRelations.find((oldRelation) => {\n return oldRelation[name] === relation[name];\n });\n })\n .filter(Boolean)\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.insert(newRelations).into(joinTable.name).onConflict().ignore();\n }\n });\n};\n\nexport { load, sync };\n"],"names":["ids"],"mappings":";AAeA,MAAM,OAAO,OAAO,KAAsB,EAAE,aAAa,kBAA+B;AACtF,QAAM,UAAU,CAAA;AAGhB,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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":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/services/entity-validator/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,OAAO,EAAO,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAa7D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,aAAa,EAAE;QAEb,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAErB,EAAE,CAAC,EAAE,MAAM,CAAC;QAGZ,OAAO,CAAC,EAAE,gBAAgB,CAAC;KAC5B,CAAC;IAEF,eAAe,EAAE,MAAM,EAAE,CAAC;IAG1B,cAAc,EAAE,OAAO,CAAC,eAAe,CAAC,MAAM,EAAE,CAAC;IACjD,sBAAsB,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;CAC/E,CAAC;AAWF,UAAU,gBAAgB;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAmhBD,QAAA,MAAM,eAAe,EAAE,OAAO,CAAC,eAAe,CAAC,eAG9C,CAAC;AAEF,eAAe,eAAe,CAAC"}
@@ -77,7 +77,9 @@ const createComponentValidator = (createOrUpdate) => ({
77
77
  attr: { required: true },
78
78
  updatedAttribute
79
79
  });
80
- validator2 = addMinMax(validator2, { attr, updatedAttribute });
80
+ if (!isDraft) {
81
+ validator2 = addMinMax(validator2, { attr, updatedAttribute });
82
+ }
81
83
  return validator2;
82
84
  }
83
85
  let validator = createModelValidator(createOrUpdate)(
@@ -115,7 +117,9 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute, compone
115
117
  attr: { required: true },
116
118
  updatedAttribute
117
119
  });
118
- validator = addMinMax(validator, { attr, updatedAttribute });
120
+ if (!isDraft) {
121
+ validator = addMinMax(validator, { attr, updatedAttribute });
122
+ }
119
123
  return validator;
120
124
  };
121
125
  const createRelationValidator = ({
@@ -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 validator = addMinMax(validator, { attr, updatedAttribute });\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 validator = addMinMax(validator, { attr, updatedAttribute });\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;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,c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,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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AAA,QAAQ,QAAQ,GAAG;AACd,yBAAA,SAAS,OAAO,QAAQ;AAAA,gBACjC;AAAA,cACF;AAAA,YAAA;AAAA,aAED,MAAM;AAAA,QACX;AAAA,MAGF;AAEO,aAAA;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EAAA;AAEL;AAMA,MAAM,sBAAsB,OAAO,iBAAuC,OAAO;AAC/E,QAAM,WAA4B,CAAA;AAElC,aAAW,CAAC,KAAK,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;;"}
@@ -74,7 +74,9 @@ const createComponentValidator = (createOrUpdate) => ({
74
74
  attr: { required: true },
75
75
  updatedAttribute
76
76
  });
77
- validator2 = addMinMax(validator2, { attr, updatedAttribute });
77
+ if (!isDraft) {
78
+ validator2 = addMinMax(validator2, { attr, updatedAttribute });
79
+ }
78
80
  return validator2;
79
81
  }
80
82
  let validator = createModelValidator(createOrUpdate)(
@@ -112,7 +114,9 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute, compone
112
114
  attr: { required: true },
113
115
  updatedAttribute
114
116
  });
115
- validator = addMinMax(validator, { attr, updatedAttribute });
117
+ if (!isDraft) {
118
+ validator = addMinMax(validator, { attr, updatedAttribute });
119
+ }
116
120
  return validator;
117
121
  };
118
122
  const createRelationValidator = ({