Skip to content

Commit

Permalink
fix: named tab being required in generated types without any required…
Browse files Browse the repository at this point in the history
… fields (#6324)
  • Loading branch information
paulpopus committed May 13, 2024
1 parent 890c21d commit aa5ad47
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 1 deletion.
88 changes: 88 additions & 0 deletions packages/payload/src/utilities/configToJSONSchema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
{
Expand Down Expand Up @@ -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',
})
})
})
8 changes: 7 additions & 1 deletion packages/payload/src/utilities/configToJSONSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit aa5ad47

Please sign in to comment.