Skip to content

Commit

Permalink
fix(schema-extraction): check for _required field in validation rules (
Browse files Browse the repository at this point in the history
…#6151)

* fix(schema-extraction): check for _required field in validation rules

* test(schema): add test case for extraction on explicit optional field

---------

Co-authored-by: Espen Hovlandsdal <[email protected]>
  • Loading branch information
sgulseth and rexxars authored Apr 1, 2024
1 parent 5756753 commit 5ba26a5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/@sanity/schema/src/sanity/extractSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions packages/@sanity/schema/test/extractSchema/extractSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,12 @@ describe('Extract schema test', () => {
type: 'string',
validation: (Rule) => Rule.required(),
}),
{
title: 'Another Title',
name: 'anotherTitle',
type: 'string',
validation: {_required: 'required'},
},
],
},
],
Expand All @@ -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', () => {
Expand All @@ -422,6 +429,18 @@ describe('Extract schema test', () => {
type: 'string',
validation: (Rule) => Rule.required(),
}),
{
title: 'Another Title',
name: 'anotherTitle',
type: 'string',
validation: {_required: 'required'},
},
{
title: 'Optional Title',
name: 'optionalTitle',
type: 'string',
validation: {_required: 'optional'},
},
],
},
],
Expand All @@ -435,6 +454,8 @@ 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)
expect(book.attributes.optionalTitle.optional).toBe(true)
})

describe('can handle `list` option that is not an array', () => {
Expand Down

0 comments on commit 5ba26a5

Please sign in to comment.