diff --git a/packages/payload/src/utilities/configToJSONSchema.spec.ts b/packages/payload/src/utilities/configToJSONSchema.spec.ts index 6808fb1e193..ca000cb72a0 100644 --- a/packages/payload/src/utilities/configToJSONSchema.spec.ts +++ b/packages/payload/src/utilities/configToJSONSchema.spec.ts @@ -5,6 +5,7 @@ import { configToJSONSchema } from './configToJSONSchema.js' describe('configToJSONSchema', () => { it('should handle optional arrays with required fields', async () => { + // @ts-expect-error const config: Config = { collections: [ { @@ -58,4 +59,91 @@ describe('configToJSONSchema', () => { type: 'object', }) }) + + it('should handle tabs and named tabs with required fields', async () => { + // @ts-expect-error + const config: Config = { + collections: [ + { + fields: [ + { + type: 'tabs', + tabs: [ + { + label: 'unnamedTab', + fields: [ + { + type: 'text', + name: 'fieldInUnnamedTab', + }, + ], + }, + { + label: 'namedTab', + name: 'namedTab', + fields: [ + { + type: 'text', + name: 'fieldInNamedTab', + }, + ], + }, + { + label: 'namedTabWithRequired', + name: 'namedTabWithRequired', + fields: [ + { + type: 'text', + name: 'fieldInNamedTab', + required: true, + }, + ], + }, + ], + }, + ], + slug: 'test', + timestamps: false, + }, + ], + } + + const sanitizedConfig = await sanitizeConfig(config) + const schema = configToJSONSchema(sanitizedConfig, 'text') + + expect(schema?.definitions?.test).toStrictEqual({ + additionalProperties: false, + properties: { + id: { + type: 'string', + }, + fieldInUnnamedTab: { + type: ['string', 'null'], + }, + namedTab: { + additionalProperties: false, + type: 'object', + properties: { + fieldInNamedTab: { + type: ['string', 'null'], + }, + }, + required: [], + }, + namedTabWithRequired: { + additionalProperties: false, + type: 'object', + properties: { + fieldInNamedTab: { + type: 'string', + }, + }, + required: ['fieldInNamedTab'], + }, + }, + required: ['id', 'namedTabWithRequired'], + title: 'Test', + type: 'object', + }) + }) }) diff --git a/packages/payload/src/utilities/configToJSONSchema.ts b/packages/payload/src/utilities/configToJSONSchema.ts index 7b07bdce172..73bfbb7ec61 100644 --- a/packages/payload/src/utilities/configToJSONSchema.ts +++ b/packages/payload/src/utilities/configToJSONSchema.ts @@ -466,7 +466,13 @@ export function fieldsToJSONSchema( additionalProperties: false, ...childSchema, }) - requiredFieldNames.add(tab.name) + + // If the named tab has any required fields then we mark this as required otherwise it should be optional + const hasRequiredFields = tab.fields.some((subField) => fieldIsRequired(subField)) + + if (hasRequiredFields) { + requiredFieldNames.add(tab.name) + } } else { Object.entries(childSchema.properties).forEach(([propName, propSchema]) => { fieldSchemas.set(propName, propSchema)