arktype
arktype copied to clipboard
Add `userDefinedContext` to validation context
Request a feature
Add userDefinedContext
(along with objectPath
and existing root
and path
) to validation context
and userDefinedContext
to define it
🤷 Motivation
Sometimes you may want your children types to behave depending on the parent data in some way without children types actually caring about actual parent types
💡 Solution
Make context to have a variable that user can define in narrow-like function before validation, which gets removed after exiting from the tree node it was added in
const S = scope({
stringWithInheritedMaxLength: narrow(
'string',
(data, context) => data.length <= context.userDefinedContext.maxStringLength,
),
});
const UserA = S
.withContext((data) => { return {maxStringLength: data.max} })
.type({
max: 'integer>0',
name: 'stringWithInheritedMaxLength',
friends: `stringWithInheritedMaxLength[]`,
})
const UserB = S.type({
max: 'integer>0',
name: 'stringWithInheritedMaxLength',
friends: `stringWithInheritedMaxLength[]`,
}, {
userDefinedContext: (data) => { return {maxStringLength: data.max} }
})
const UserC = S.type({
max: 'integer>0',
name: 'stringWithInheritedMaxLength',
friends: `stringWithInheritedMaxLength[]`,
[userDefinedContext]: (data) => { return {maxStringLength: data.max} }
})
This context also can be passed into the validator itself, if user needs that
UserLike({name: 'foo', friends: ['bar']}, {userDefinedContext: {maxStringLength: 123}})
Same question as #842- does it seem like it would be more appropriate to just have the parent perform a final check with the context of its validated children at that point?