From a4ecae0f00c5ad41c2091f0dd7c008f43a9775a1 Mon Sep 17 00:00:00 2001 From: Sindre Gulseth Date: Fri, 29 Mar 2024 12:41:47 +0100 Subject: [PATCH] fix(schema-extraction): check for _required field in validation rules --- .../@sanity/schema/src/sanity/extractSchema.ts | 7 +++++++ .../test/extractSchema/extractSchema.test.ts | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/packages/@sanity/schema/src/sanity/extractSchema.ts b/packages/@sanity/schema/src/sanity/extractSchema.ts index 22376c0f88a..e70f909d2ae 100644 --- a/packages/@sanity/schema/src/sanity/extractSchema.ts +++ b/packages/@sanity/schema/src/sanity/extractSchema.ts @@ -315,12 +315,19 @@ function isFieldRequired(field: ObjectField): boolean { }, }, ) as Rule + if (typeof rule === 'function') { rule(proxy) if (required) { return true } } + + if (typeof rule === 'object' && rule !== null && '_required' in rule) { + if (rule._required === 'required') { + return true + } + } } return false diff --git a/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts b/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts index d8df385f807..396f364917b 100644 --- a/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts +++ b/packages/@sanity/schema/test/extractSchema/extractSchema.test.ts @@ -387,6 +387,12 @@ describe('Extract schema test', () => { type: 'string', validation: (Rule) => Rule.required(), }), + { + title: 'Another Title', + name: 'anotherTitle', + type: 'string', + validation: {_required: 'required'}, + }, ], }, ], @@ -400,6 +406,7 @@ describe('Extract schema test', () => { 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(true) + expect(book.attributes.anotherTitle.optional).toBe(true) }) test('can extract with enforceRequiredFields', () => { @@ -422,6 +429,12 @@ describe('Extract schema test', () => { type: 'string', validation: (Rule) => Rule.required(), }), + { + title: 'Another Title', + name: 'anotherTitle', + type: 'string', + validation: {_required: 'required'}, + }, ], }, ], @@ -435,6 +448,7 @@ describe('Extract schema test', () => { 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) + expect(book.attributes.anotherTitle.optional).toBe(false) }) describe('can handle `list` option that is not an array', () => {