diff --git a/packages/@sanity/schema/src/sanity/extractSchema.ts b/packages/@sanity/schema/src/sanity/extractSchema.ts index 1f80d3daba85..189f9748e22c 100644 --- a/packages/@sanity/schema/src/sanity/extractSchema.ts +++ b/packages/@sanity/schema/src/sanity/extractSchema.ts @@ -210,7 +210,7 @@ export function extractSchema( attributes[field.name] = { type: 'objectAttribute', value, - optional: extractOptions.enforceRequiredFields ? fieldIsRequired : true, + optional: extractOptions.enforceRequiredFields ? fieldIsRequired === false : true, } } diff --git a/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts b/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts index 94814ed49475..07260273a220 100644 --- a/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts +++ b/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert' import {describe, expect, test} from '@jest/globals' -import {defineType} from '@sanity/types' +import {defineField, defineType} from '@sanity/types' import {Schema} from '../../src/legacy/Schema' import {extractSchema} from '../../src/sanity/extractSchema' @@ -367,6 +367,41 @@ describe('Extract schema test', () => { ]) }) + test('can extract with enforceRequiredFields', () => { + const schema1 = createSchema({ + name: 'test', + types: [ + { + title: 'Book', + name: 'book', + type: 'document', + fields: [ + { + title: 'Title', + name: 'title', + type: 'string', + }, + defineField({ + title: 'Subtitle', + name: 'subtitle', + type: 'string', + validation: (Rule) => Rule.required(), + }), + ], + }, + ], + }) + + const extracted = extractSchema(schema1, {enforceRequiredFields: true}) + + const book = extracted.find((type) => type.name === 'book') + expect(book).toBeDefined() + assert(book !== undefined) // this is a workaround for TS, but leave the expect above for clarity in case of failure + assert(book.type === 'document') // this is a workaround for TS, but leave the expect above for clarity in case of failure + expect(book.attributes.title.optional).toBe(true) + expect(book.attributes.subtitle.optional).toBe(false) + }) + describe('Can extract sample fixtures', () => { const cases = Object.keys(schemaFixtures).map((schemaName) => { const schema = createSchema(schemaFixtures[schemaName])