arktype icon indicating copy to clipboard operation
arktype copied to clipboard

Add `userDefinedContext` to validation context

Open Dimava opened this issue 1 year ago • 1 comments

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

Dimava avatar Aug 18 '23 21:08 Dimava

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?

ssalbdivad avatar May 14 '24 17:05 ssalbdivad