joi
joi copied to clipboard
external function applied to alternative schemas
Context
- node version: 14.17
- module version with issue: 17.6
- last module version without issue: N/A
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): None
- any other relevant information:
What are you trying to achieve or the steps to reproduce?
I have two schemas with their own external functions, then those 2 schemas are wrapped in an alternatives schema. I expected only the external function from the schema that passed validation to get called. Instead what seems to happen is every schema's external function is called even if that schema fails validation. Then the value from the invalid schema's external function is handed off to the next schema's external function.
import Joi from "joi"
(async function fn() {
const schema1 = Joi.string().valid("foo")
.external( val => `schema1-${val}` )
const schema2 = Joi.string().valid("bar")
.external( val => `schema2-${val}` )
const altSchema = Joi.alternatives().try( schema1, schema2 )
console.log( await altSchema.validateAsync( "foo" ) )
// => schema1-foo
console.log( await altSchema.validateAsync( "bar" ) )
// => schema2-schema1-bar
})()
What was the result you got?
First validation - Behaves as expected:
- "foo" is passed to schema1 and passes validation
- schema1.external fn fires, which returns "schema1-foo"
- schema2 validation and external are skipped
Second validation - Unexpected Behavior:
- "foo" is passed to schema1 and fails validation (expected)
- schema1.external fn fires even though validation failed (unexpected)
- transformed "schema1-bar" is passed to schema2
- schema2 passes validation because it's validating original value?
- schema2.external transforms value to "schema2-schema1-bar"
What result did you expect?
Second validation - Expected Behavior:
- "foo" is passed to schema1 and fails validation
- schema1.external doesn't fire, doesn't transform value for schema2
- schema2 passes validation, schema2.external is the only external fn to get called
- result is "schema2-bar"