.when() does not work
Closed this issue · 2 comments
alesdvorakcz commented
Hello,
I am not sure if its a bug or just not supported feature. It looks like .when() is ignored.
Example Joi schema:
Joi.object()
.keys({
version: Joi.string(),
rules: Joi.array()
.items(
Joi.object()
.keys({
ruleName: Joi.string().required()
})
.when(
Joi.object()
.keys({ ruleName: Joi.valid('xxx') })
.unknown(),
{ then: Joi.object().keys({ key1: Joi.string().required() }) }
)
.when(
Joi.object()
.keys({ ruleName: Joi.valid('yyy') })
.unknown(),
{ then: Joi.object().keys({ key2: Joi.string().required() }) }
)
.strict()
)
.required()
.min(1)
})
.strict();
is converted into:
{
"type": "object",
"properties": {
"version": {
"type": "string"
},
"rules": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"ruleName": {
"type": "string"
}
},
"required": [
"ruleName"
],
"additionalProperties": false
}
}
},
"required": [
"rules"
],
"additionalProperties": false
}
kenspirit commented
Hi @alesdvorakcz, current support for alternatives
and when
is something written like this in fixtures folder for your reference:
.when('gender', {
is: 'Male',
then: joi.string().not().empty().required(),
otherwise: joi.optional()
})
Not sure if you can try to adjust your joi definition, or submit one PR if you can.
What is more, what is your expected output JSON schema?
kenspirit commented
@alesdvorakcz Released version 4.0.0 now can convert the joi to json-draft-2019-09 to below format:
{
"type": "object",
"properties": {
"version": {
"type": "string"
},
"rules": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"ruleName": {
"type": "string"
}
},
"required": ["ruleName"],
"additionalProperties": false,
"allOf": [{
"if": {
"type": "object",
"properties": {
"ruleName": {
"const": "xxx"
}
},
"additionalProperties": true
},
"then": {
"type": "object",
"properties": {
"key1": {
"type": "string"
}
},
"required": ["key1"],
"additionalProperties": false
}
}, {
"if": {
"type": "object",
"properties": {
"ruleName": {
"const": "yyy"
}
},
"additionalProperties": true
},
"then": {
"type": "object",
"properties": {
"key2": {
"type": "string"
}
},
"required": ["key2"],
"additionalProperties": false
}
}]
}
}
},
"required": ["rules"],
"additionalProperties": false
}