@strapi/core 5.0.0-beta.11 → 5.0.0-beta.12

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.
@@ -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 from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype Entity = {\n id: ID;\n [key: string]: unknown;\n} | null;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface AttributeValidatorMetas {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Entity;\n}\n\ninterface ModelValidatorMetas {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: 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 { attr, updatedAttribute }: 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)({ model, data: item }, { isDraft }).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 // FIXME: v4 was broken\n let validator = createModelValidator(createOrUpdate)(\n { model, data: updatedAttribute.value },\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 }: 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(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }))\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 (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n { isDraft }: ValidatorContext\n ) => {\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 validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\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) =>\n (metas: AttributeValidatorMetas, 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') {\n validator = createComponentValidator(createOrUpdate)(\n { attr: metas.attr, updatedAttribute: metas.updatedAttribute },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\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 ({ 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 };\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?: 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 { model, data, entity },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test('relations-test', 'check that all relations exist', async function (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 .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","isObject","data","isEmpty","isNil","castArray","mergeWith","isArray","value","uniqBy"],"mappings":";;;;;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAAA;A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AAsB,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 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};\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 AttributeValidatorMetas extends WithComponentContext {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Modules.EntityValidator.Entity;\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 (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n { isDraft }: ValidatorContext\n ) => {\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 validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\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) =>\n (metas: AttributeValidatorMetas, 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') {\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 = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext as ComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n // TODO: fix! query layer fails when building a where for dynamic\n // zones\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n const newComponentContext = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n };\n\n validator = createDzValidator(createOrUpdate)(\n { ...metas, componentContext: newComponentContext as ComponentContext },\n options\n );\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\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","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;AAkDxC,MAAM,YAAY,C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BACjC;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,IAAO,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;;"}
@@ -52,7 +52,11 @@ const addDefault = (createOrUpdate) => {
52
52
  };
53
53
  };
54
54
  const preventCast = (validator) => validator.transform((val, originalVal) => originalVal);
55
- const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
55
+ const createComponentValidator = (createOrUpdate) => ({
56
+ attr,
57
+ updatedAttribute,
58
+ componentContext
59
+ }, { isDraft }) => {
56
60
  const model = strapi.getModel(attr.component);
57
61
  if (!model) {
58
62
  throw new Error("Validation failed: Model not found");
@@ -60,7 +64,10 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
60
64
  if (attr?.repeatable) {
61
65
  let validator2 = yup.array().of(
62
66
  yup.lazy(
63
- (item) => createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }).notNull()
67
+ (item) => createModelValidator(createOrUpdate)(
68
+ { componentContext, model, data: item },
69
+ { isDraft }
70
+ ).notNull()
64
71
  )
65
72
  );
66
73
  validator2 = addRequiredValidation(createOrUpdate)(validator2, {
@@ -71,7 +78,11 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
71
78
  return validator2;
72
79
  }
73
80
  let validator = createModelValidator(createOrUpdate)(
74
- { model, data: updatedAttribute.value },
81
+ {
82
+ model,
83
+ data: updatedAttribute.value,
84
+ componentContext
85
+ },
75
86
  { isDraft }
76
87
  );
77
88
  validator = addRequiredValidation(createOrUpdate)(validator, {
@@ -80,7 +91,7 @@ const createComponentValidator = (createOrUpdate) => ({ attr, updatedAttribute }
80
91
  });
81
92
  return validator;
82
93
  };
83
- const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isDraft }) => {
94
+ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute, componentContext }, { isDraft }) => {
84
95
  let validator;
85
96
  validator = yup.array().of(
86
97
  yup.lazy((item) => {
@@ -88,7 +99,12 @@ const createDzValidator = (createOrUpdate) => ({ attr, updatedAttribute }, { isD
88
99
  const schema = yup.object().shape({
89
100
  __component: yup.string().required().oneOf(Object.keys(strapi.components))
90
101
  }).notNull();
91
- return model ? schema.concat(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft })) : schema;
102
+ return model ? schema.concat(
103
+ createModelValidator(createOrUpdate)(
104
+ { model, data: item, componentContext },
105
+ { isDraft }
106
+ )
107
+ ) : schema;
92
108
  })
93
109
  // FIXME: yup v1
94
110
  );
@@ -133,12 +149,37 @@ const createAttributeValidator = (createOrUpdate) => (metas, options) => {
133
149
  validator = createScalarAttributeValidator(createOrUpdate)(metas, options);
134
150
  } else {
135
151
  if (metas.attr.type === "component") {
152
+ const pathToComponent = [
153
+ ...metas?.componentContext?.pathToComponent ?? [],
154
+ metas.updatedAttribute.name
155
+ ];
156
+ const repeatableData = metas.attr.repeatable && pathToComponent.length === 1 ? metas.updatedAttribute.value : metas.componentContext?.repeatableData;
157
+ const newComponentContext = {
158
+ ...metas?.componentContext ?? {},
159
+ pathToComponent,
160
+ repeatableData
161
+ };
136
162
  validator = createComponentValidator(createOrUpdate)(
137
- { attr: metas.attr, updatedAttribute: metas.updatedAttribute },
163
+ {
164
+ componentContext: newComponentContext,
165
+ attr: metas.attr,
166
+ updatedAttribute: metas.updatedAttribute
167
+ },
138
168
  options
139
169
  );
140
170
  } else if (metas.attr.type === "dynamiczone") {
141
- validator = createDzValidator(createOrUpdate)(metas, options);
171
+ const pathToComponent = [
172
+ ...metas?.componentContext?.pathToComponent ?? [],
173
+ metas.updatedAttribute.name
174
+ ];
175
+ const newComponentContext = {
176
+ ...metas?.componentContext ?? {},
177
+ pathToComponent
178
+ };
179
+ validator = createDzValidator(createOrUpdate)(
180
+ { ...metas, componentContext: newComponentContext },
181
+ options
182
+ );
142
183
  } else if (metas.attr.type === "relation") {
143
184
  validator = createRelationValidator(createOrUpdate)(
144
185
  {
@@ -153,7 +194,7 @@ const createAttributeValidator = (createOrUpdate) => (metas, options) => {
153
194
  validator = addDefault(createOrUpdate)(validator, metas);
154
195
  return validator;
155
196
  };
156
- const createModelValidator = (createOrUpdate) => ({ model, data, entity }, options) => {
197
+ const createModelValidator = (createOrUpdate) => ({ componentContext, model, data, entity }, options) => {
157
198
  const writableAttributes = model ? getWritableAttributes(model) : [];
158
199
  const schema = writableAttributes.reduce(
159
200
  (validators2, attributeName) => {
@@ -161,7 +202,8 @@ const createModelValidator = (createOrUpdate) => ({ model, data, entity }, optio
161
202
  attr: model.attributes[attributeName],
162
203
  updatedAttribute: { name: attributeName, value: prop(attributeName, data) },
163
204
  model,
164
- entity
205
+ entity,
206
+ componentContext
165
207
  };
166
208
  const validator = createAttributeValidator(createOrUpdate)(metas, options);
167
209
  validators2[attributeName] = validator;
@@ -180,22 +222,42 @@ const createValidateEntity = (createOrUpdate) => {
180
222
  );
181
223
  }
182
224
  const validator = createModelValidator(createOrUpdate)(
183
- { model, data, entity },
225
+ {
226
+ model,
227
+ data,
228
+ entity,
229
+ componentContext: {
230
+ // Set up the initial component context.
231
+ // Keeping track of parent content type context in which a component will be used.
232
+ // This is necessary to validate component field constraints such as uniqueness.
233
+ parentContent: {
234
+ id: entity?.id,
235
+ model,
236
+ options
237
+ },
238
+ pathToComponent: [],
239
+ repeatableData: []
240
+ }
241
+ },
184
242
  {
185
243
  isDraft: options?.isDraft ?? false,
186
244
  locale: options?.locale ?? null
187
245
  }
188
- ).test("relations-test", "check that all relations exist", async function(data2) {
189
- try {
190
- await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
191
- } catch (e) {
192
- return this.createError({
193
- path: this.path,
194
- message: e instanceof ValidationError && e.message || "Invalid relations"
195
- });
246
+ ).test(
247
+ "relations-test",
248
+ "check that all relations exist",
249
+ async function relationsValidation(data2) {
250
+ try {
251
+ await checkRelationsExist(buildRelationsStore({ uid: model.uid, data: data2 }));
252
+ } catch (e) {
253
+ return this.createError({
254
+ path: this.path,
255
+ message: e instanceof ValidationError && e.message || "Invalid relations"
256
+ });
257
+ }
258
+ return true;
196
259
  }
197
- return true;
198
- }).required();
260
+ ).required();
199
261
  return validateYupSchema(validator, {
200
262
  strict: false,
201
263
  abortEarly: false
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport validators from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype Entity = {\n id: ID;\n [key: string]: unknown;\n} | null;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface AttributeValidatorMetas {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Entity;\n}\n\ninterface ModelValidatorMetas {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: 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 { attr, updatedAttribute }: 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)({ model, data: item }, { isDraft }).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 // FIXME: v4 was broken\n let validator = createModelValidator(createOrUpdate)(\n { model, data: updatedAttribute.value },\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 }: 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(createModelValidator(createOrUpdate)({ model, data: item }, { isDraft }))\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 (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n { isDraft }: ValidatorContext\n ) => {\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 validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\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) =>\n (metas: AttributeValidatorMetas, 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') {\n validator = createComponentValidator(createOrUpdate)(\n { attr: metas.attr, updatedAttribute: metas.updatedAttribute },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\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 ({ 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 };\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?: 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 { model, data, entity },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test('relations-test', 'check that all relations exist', async function (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 .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","validators","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AAkCxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACO,SAAA;AACT;AAEA,MAAM,wBAAwB,CAAC,mBAAmC;AAChE,SA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,cAAc,GAAG;AACzD,UAAM,WAAW,YAAY;AACrB,YAAA,eAAe,OAAO,OAAO,IAAI;AACvC,YAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,GAAiB,EAAE,MAAM;AAAA,QAC3D,OAAO;AAAA,UACL,IAAI;AAAA,YACF,KAAK,aAAa,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,UACnC;AAAA,QACF;AAAA,MAAA,CACD;AAEG,UAAA,UAAU,aAAa,QAAQ;AACjC,cAAM,IAAI;AAAA,UACR,GACE,aAAa,SAAS,KACxB,wBAAwB,GAAG;AAAA,QAAA;AAAA,MAE/B;AAAA,IAAA;AAEO,aAAA,KAAK,UAAU;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport validators 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};\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 AttributeValidatorMetas extends WithComponentContext {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Modules.EntityValidator.Entity;\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 (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n { isDraft }: ValidatorContext\n ) => {\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 validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\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) =>\n (metas: AttributeValidatorMetas, 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') {\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 = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext as ComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n // TODO: fix! query layer fails when building a where for dynamic\n // zones\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n const newComponentContext = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n };\n\n validator = createDzValidator(createOrUpdate)(\n { ...metas, componentContext: newComponentContext as ComponentContext },\n options\n );\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","validators","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AAkDxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACO,SAAA;AACT;AAEA,MAAM,wBAAwB,CAAC,mBAAmC;AAChE,SAAO,CACL,WACA;AAAA,IACE,MAAM,EAAE,SAAS;AAAA,EAAA,MAEb;AACN,QAAI,gBAAgB;AAEpB,QAAI,UAAU;AACZ,UAAI,mBAAmB,YAAY;AACjC,wBAAgB,cAAc;MAAO,WAC5B,mBAAmB,UAAU;AACtC,wBAAgB,cAAc;MAChC;AAAA,IAAA,OACK;AACL,sBAAgB,cAAc;IAChC;AACO,WAAA;AAAA,EAAA;AAEX;AAEA,MAAM,aAAa,CAAC,mBAAmC;AACrD,SAAO,CACL,WACA,EAAE,W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Struct } from '@strapi/types';
1
+ import { yup } from '@strapi/utils';
2
+ import type { Schema, Struct, Modules } from '@strapi/types';
3
+ import type { ComponentContext } from '.';
3
4
  interface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {
4
5
  attr: TAttribute;
5
6
  model: Struct.ContentTypeSchema;
@@ -7,7 +8,8 @@ interface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {
7
8
  name: string;
8
9
  value: unknown;
9
10
  };
10
- entity: Record<string, unknown> | null;
11
+ entity: Modules.EntityValidator.Entity;
12
+ componentContext: ComponentContext;
11
13
  }
12
14
  interface ValidatorOptions {
13
15
  isDraft: boolean;
@@ -22,18 +24,18 @@ declare const _default: {
22
24
  enumeration: ({ attr }: {
23
25
  attr: Schema.Attribute.OfType<"enumeration"> & Schema.Attribute.EnumerationProperties<[]> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<never> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption;
24
26
  }) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
25
- boolean: () => strapiUtils.yup.BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined>;
27
+ boolean: () => yup.BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined>;
26
28
  uid: (metas: ValidatorMetas<Schema.Attribute.OfType<"uid"> & Schema.Attribute.UIDProperties<string, Schema.Attribute.UIDOptions> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxLengthOption & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
27
29
  json: () => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
28
- integer: (metas: ValidatorMetas<(Schema.Attribute.OfType<"biginteger"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxOption<string> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"integer"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => strapiUtils.yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
30
+ integer: (metas: ValidatorMetas<(Schema.Attribute.OfType<"biginteger"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxOption<string> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"integer"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
29
31
  biginteger: (metas: ValidatorMetas<Schema.Attribute.OfType<"biginteger"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxOption<string> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
30
- float: (metas: ValidatorMetas<(Schema.Attribute.OfType<"decimal"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"float"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => strapiUtils.yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
31
- decimal: (metas: ValidatorMetas<(Schema.Attribute.OfType<"decimal"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"float"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => strapiUtils.yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
32
+ float: (metas: ValidatorMetas<(Schema.Attribute.OfType<"decimal"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"float"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
33
+ decimal: (metas: ValidatorMetas<(Schema.Attribute.OfType<"decimal"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"float"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption)>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
32
34
  date: (metas: ValidatorMetas<(Schema.Attribute.OfType<"datetime"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateTimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"date"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"time"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"timestamp"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimestampValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption)>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
33
35
  time: (metas: ValidatorMetas<(Schema.Attribute.OfType<"datetime"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateTimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"date"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"time"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"timestamp"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimestampValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption)>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
34
36
  datetime: (metas: ValidatorMetas<(Schema.Attribute.OfType<"datetime"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateTimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"date"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"time"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"timestamp"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimestampValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption)>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
35
37
  timestamp: (metas: ValidatorMetas<(Schema.Attribute.OfType<"datetime"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateTimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"date"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"time"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"timestamp"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.TimestampValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption)>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
36
- blocks: (metas: any, options: any) => strapiUtils.yup.ArraySchema<any, import("yup/lib/types").AnyObject, any[] | undefined, any[] | undefined>;
38
+ blocks: (metas: any, options: any) => yup.ArraySchema<any, import("yup/lib/types").AnyObject, any[] | undefined, any[] | undefined>;
37
39
  };
38
40
  export default _default;
39
41
  //# sourceMappingURL=validators.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../../src/services/entity-validator/validators.ts"],"names":[],"mappings":"AACA,OAAO,WAAW,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAKpD,UAAU,cAAc,CAAC,UAAU,SAAS,MAAM,CAAC,SAAS,CAAC,YAAY;IACvE,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAChC,gBAAgB,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;IACnD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CACxC;AAED,UAAU,gBAAgB;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;;;;;;;;;;;;;;;;;;;;;;;AAuQD,wBAmBE"}
1
+ {"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../../src/services/entity-validator/validators.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,GAAG,CAAC;AAE1C,UAAU,cAAc,CAAC,UAAU,SAAS,MAAM,CAAC,SAAS,CAAC,YAAY;IACvE,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAChC,gBAAgB,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;IACnD,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC;IACvC,gBAAgB,EAAE,gBAAgB,CAAC;CACpC;AAED,UAAU,gBAAgB;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;;;;;;;;;;;;;;;;;;;;;;;AAwVD,wBAmBE"}
@@ -4,8 +4,6 @@ const strapiUtils = require("@strapi/utils");
4
4
  const blocksValidator = require("./blocks-validator.js");
5
5
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
6
6
  const ___default = /* @__PURE__ */ _interopDefault(_);
7
- const strapiUtils__default = /* @__PURE__ */ _interopDefault(strapiUtils);
8
- const { yup } = strapiUtils__default.default;
9
7
  const addMinLengthValidator = (validator, {
10
8
  attr
11
9
  }, { isDraft }) => {
@@ -37,7 +35,8 @@ const addUniqueValidator = (validator, {
37
35
  attr,
38
36
  model,
39
37
  updatedAttribute,
40
- entity
38
+ entity,
39
+ componentContext
41
40
  }, options) => {
42
41
  if (attr.type !== "uid" && !attr.unique) {
43
42
  return validator;
@@ -50,19 +49,61 @@ const addUniqueValidator = (validator, {
50
49
  if (!isPublish && value === entity?.[updatedAttribute.name]) {
51
50
  return true;
52
51
  }
53
- const record = await strapi.db.query(model.uid).findOne({
54
- where: {
55
- locale: options.locale,
56
- publishedAt: options.isDraft ? null : { $notNull: true },
57
- [updatedAttribute.name]: value,
58
- ...entity?.id ? { id: { $ne: entity.id } } : {}
52
+ let queryUid;
53
+ let queryWhere = {};
54
+ if (componentContext) {
55
+ const hasRepeatableData = componentContext.repeatableData.length > 0;
56
+ if (hasRepeatableData) {
57
+ const { name: updatedName, value: updatedValue } = updatedAttribute;
58
+ const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join(".");
59
+ const values = componentContext.repeatableData.map((item) => {
60
+ return pathToCheck.split(".").reduce((acc, key) => acc[key], item);
61
+ });
62
+ const isUpdatedAttributeRepeatedInThisEntity = values.filter((value2) => value2 === updatedValue).length > 1;
63
+ if (isUpdatedAttributeRepeatedInThisEntity) {
64
+ return false;
65
+ }
59
66
  }
60
- });
61
- return !record;
67
+ const {
68
+ model: parentModel,
69
+ options: parentOptions,
70
+ id: excludeId
71
+ } = componentContext.parentContent;
72
+ queryUid = parentModel.uid;
73
+ const whereConditions = {};
74
+ const isParentDraft = parentOptions && parentOptions.isDraft;
75
+ whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };
76
+ if (parentOptions?.locale) {
77
+ whereConditions.locale = parentOptions.locale;
78
+ }
79
+ if (excludeId && !Number.isNaN(excludeId)) {
80
+ whereConditions.id = { $ne: excludeId };
81
+ }
82
+ queryWhere = {
83
+ ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {
84
+ [updatedAttribute.name]: value
85
+ }),
86
+ ...whereConditions
87
+ };
88
+ } else {
89
+ queryUid = model.uid;
90
+ const scalarAttributeWhere = {
91
+ [updatedAttribute.name]: value
92
+ };
93
+ scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };
94
+ if (options?.locale) {
95
+ scalarAttributeWhere.locale = options.locale;
96
+ }
97
+ if (entity?.id) {
98
+ scalarAttributeWhere.id = { $ne: entity.id };
99
+ }
100
+ queryWhere = scalarAttributeWhere;
101
+ }
102
+ return !await strapi.db.query(queryUid).findOne({ where: queryWhere });
62
103
  });
63
104
  };
64
105
  const stringValidator = (metas, options) => {
65
- let schema = yup.string().transform((val, originalVal) => originalVal);
106
+ let schema = strapiUtils.yup.string().transform((val, originalVal) => originalVal);
66
107
  schema = addMinLengthValidator(schema, metas, options);
67
108
  schema = addMaxLengthValidator(schema, metas);
68
109
  schema = addStringRegexValidator(schema, metas);
@@ -78,28 +119,28 @@ const uidValidator = (metas, options) => {
78
119
  return schema.matches(/^[A-Za-z0-9-_.~]*$/);
79
120
  };
80
121
  const enumerationValidator = ({ attr }) => {
81
- return yup.string().oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null));
122
+ return strapiUtils.yup.string().oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null));
82
123
  };
83
124
  const integerValidator = (metas, options) => {
84
- let schema = yup.number().integer();
125
+ let schema = strapiUtils.yup.number().integer();
85
126
  schema = addMinIntegerValidator(schema, metas);
86
127
  schema = addMaxIntegerValidator(schema, metas);
87
128
  schema = addUniqueValidator(schema, metas, options);
88
129
  return schema;
89
130
  };
90
131
  const floatValidator = (metas, options) => {
91
- let schema = yup.number();
132
+ let schema = strapiUtils.yup.number();
92
133
  schema = addMinFloatValidator(schema, metas);
93
134
  schema = addMaxFloatValidator(schema, metas);
94
135
  schema = addUniqueValidator(schema, metas, options);
95
136
  return schema;
96
137
  };
97
138
  const bigintegerValidator = (metas, options) => {
98
- const schema = yup.mixed();
139
+ const schema = strapiUtils.yup.mixed();
99
140
  return addUniqueValidator(schema, metas, options);
100
141
  };
101
142
  const datesValidator = (metas, options) => {
102
- const schema = yup.mixed();
143
+ const schema = strapiUtils.yup.mixed();
103
144
  return addUniqueValidator(schema, metas, options);
104
145
  };
105
146
  const validators = {
@@ -109,9 +150,9 @@ const validators = {
109
150
  password: stringValidator,
110
151
  email: emailValidator,
111
152
  enumeration: enumerationValidator,
112
- boolean: () => yup.boolean(),
153
+ boolean: () => strapiUtils.yup.boolean(),
113
154
  uid: uidValidator,
114
- json: () => yup.mixed(),
155
+ json: () => strapiUtils.yup.mixed(),
115
156
  integer: integerValidator,
116
157
  biginteger: bigintegerValidator,
117
158
  float: floatValidator,