fix: named tab being required in generated types without any required fields (#6324)

This commit is contained in:
Paul
2024-05-13 14:55:48 -03:00
committed by GitHub
parent 890c21dda4
commit aa5ad47177
2 changed files with 95 additions and 1 deletions

View File

@@ -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',
})
})
})

View File

@@ -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)