fix: typescriptSchema override required to false (#11941)

### What?
Previously if you used the typescriptSchema and `returned: false`, the
field would still be required anyways.

### Why?
We were adding fields to be required on the collection without comparing
the returned schema from typescriptSchema functions.

### How?
This changes the order of logic so that `requiredFieldNames` on the
collection is only after running and checking the field schema.
This commit is contained in:
Dan Ribbens
2025-04-01 11:35:31 -04:00
committed by GitHub
parent 373f6d1032
commit 968a066f45
2 changed files with 35 additions and 3 deletions

View File

@@ -411,4 +411,36 @@ describe('configToJSONSchema', () => {
expect(schema?.definitions?.SharedBlock).toBeDefined()
})
it('should allow overriding required to false', async () => {
// @ts-expect-error
const config: Config = {
collections: [
{
slug: 'test',
fields: [
{
name: 'title',
type: 'text',
required: true,
defaultValue: 'test',
typescriptSchema: [
() => ({
type: 'string',
required: false,
}),
],
},
],
timestamps: false,
},
],
}
const sanitizedConfig = await sanitizeConfig(config)
const schema = configToJSONSchema(sanitizedConfig, 'text')
// @ts-expect-error
expect(schema.definitions.test.properties.title.required).toStrictEqual(false)
})
})

View File

@@ -258,9 +258,6 @@ export function fieldsToJSONSchema(
properties: Object.fromEntries(
fields.reduce((fieldSchemas, field, index) => {
const isRequired = fieldAffectsData(field) && fieldIsRequired(field)
if (isRequired) {
requiredFieldNames.add(field.name)
}
const fieldDescription = entityOrFieldToJsDocs({ entity: field, i18n })
const baseFieldSchema: JSONSchema4 = {}
@@ -706,6 +703,9 @@ export function fieldsToJSONSchema(
}
if (fieldSchema && fieldAffectsData(field)) {
if (isRequired && fieldSchema.required !== false) {
requiredFieldNames.add(field.name)
}
fieldSchemas.set(field.name, fieldSchema)
}