问题
I have following json I am trying to validate using @hapi/Joi 16+. It largely works up to 3 levels. But after that it wouldn't validate the alternative files
. folder
schema get validated fine. I am hoping for optimised solution that would validate deep nested array.
In here ONLY folders suppose to have optional children
. Files schema should NOT have children
. Hence I am using alternatives.
const data = [{
id: '1', //UUID
type: 'folder',
children: [{
id: '2', //UUID
type: 'folder',
children: []
},
{
id: '3', //UUID
type: 'file',
}, {
id: '4', //UUID
type: 'folder',
children: [{
id: '5', //UUID
type: 'folder',
children: [{
id: '7', //UUID
type: 'file'
}, {
id: '6', //UUID
type: 'folder',
children: [{
id: '7', //UUID
type: 'file'
}]
}]
}]
}
]
}]
JOI schema
import Joi from '@hapi/joi';
const validTypes = ['file', 'jpg'];
const files = Joi.object({
id: Joi.number().integer(),
type: Joi.string()
.valid(...validTypes)
.required()
});
const children = Joi.object({
children: Joi.array()
.items(Joi.alternatives(Joi.link('#children'), files))
.optional(),
type: Joi.string()
}).id('#children');
const fileSystem = Joi.object({
children: Joi.array().items(children),
id: Joi.number().integer(),
type: Joi.string()
.alphanum()
.required()
});
export const fileSystemSchema = Joi.array().items(fileSystem);
来源:https://stackoverflow.com/questions/60695894/joi-deep-nested-recursive-array-of-alternative-objects-validation