-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
Describe the problem you are trying to fix (provide as much context as possible)
I have a configuration file, where an array is included containing unique elements.
JSON:
{
"list": [1, 2 ,3]
}Schema:
const schema = Joi.object().keys({
list: Joi.array().items(Joi.number()).unique()
})Once this has been validated with joi, I want to convert this array into a Set for fast O(1) complexity lookups.
Which API (or modification of the current API) do you suggest to solve that problem ?
While I can do the casting manually in a post-processing stage, I think an any.cast() option, which converts the rule value post-validation, could provide a great deal of value. Not only for this case, but others as well (eg. object to Map conversion). There is already precedent for such an output modifier with the any.raw() rule.
A simple and powerful way to do this, would be to just pass a method:
any.cast(fn)
Outputs the value returned from calling fn(value) instead of the casted or raw value.
const schema = Joi.object().keys({
list: Joi.array().items(Joi.number()).unique().cast((v) => new Set(v))
})The downside, is that it requires handling errors in the casting function, and that it might be abused to apply other stateful changes to the output. Eg. Joi.any().optional().cast(() => new Date()) to create a rule that adds the current date to an object. If that is the implementation, any.transform() might actually be a better name for it.
Are you ready to work on a pull request if your suggestion is accepted ?
Yes