У меня есть следующая схема joi:
const schema = Joi.object({
name: Joi.string().required(),
resource: Joi.object({
uri: Joi.string(),
}),
fov: Joi.alternatives().when('resource.uri', {
is: Joi.string().regex(/\.jpg$/),
then: Joi.any().forbidden(),
otherwise: Joi.number().required()
})
});
Я ожидал, что когда я пришлю следующий орган запроса
{
name: 'name',
resource: {
uri: 'file.jpg'
},
fov: 10
}
Я получаю ошибку, потому что регулярное выражение условия when.is будет соответствовать 'file.jpg'
и поэтому fov
будет проверяться как Joi.any().forbidden()
. Но проверка, похоже, игнорируется. У вас есть идеи, что я делаю неправильно?
Спасибо за вашу помощь!
Отвечая на вопрос, я отвечаю:
Мой первоначальный объект проверки выглядел следующим образом:
resource: Joi.object({
uri: Joi.alternatives().try(
Joi.string(),
Joi.array().max(config.objectTargets.maxImages).items(Joi.string())
),
fov: Joi.alternatives().when('resource.uri', {
is: Joi.string().regex(/\.wto$/),
then: Joi.any().forbidden(),
otherwise: Joi.number().required()
}),
})
Таким образом, он искал resource.uri
в свойстве resource
. Решение заключается в том, чтобы условие when было ссылкой на просто uri
, как здесь:
resource: Joi.object({
uri: Joi.alternatives().try(
Joi.string(),
Joi.array().max(config.objectTargets.maxImages).items(Joi.string())
),
fov: Joi.alternatives().when('uri', {
is: Joi.string().regex(/\.wto$/),
then: Joi.any().forbidden(),
otherwise: Joi.number().required()
}),
})
Извините за то, что вы не были более внимательны перед
Ну, кажется, что он отлично работает, но ошибка не выбрасывается, она включена в возвращаемое значение:
const Joi = require('joi');
const schema = Joi.object({
name: Joi.string().required(),
resource: Joi.object({
uri: Joi.string(),
}),
fov: Joi.alternatives().when('resource.uri', {
is: Joi.string().regex(/\.jpg$/),
then: Joi.any().forbidden(),
otherwise: Joi.number().required()
})
});
const testVal = format => ({
name: 'name',
resource: {
uri: format
},
fov: 10
});
const png = 'file.png';
const jpg = 'file.jpg';
const testPng = testVal(png);
const testJpg = testVal(jpg);
console.log(Joi.validate(testJpg, schema));
console.log("------------------------------");
console.log(Joi.validate(testPng, schema));
Дает этот результат:
{ error:
{ ValidationError: child "fov" fails because ["fov" is not allowed]
at Object.exports.process (/home/boehm-s/tmp/node_modules/joi/lib/errors.js:196:19)
at internals.Object._validateWithOptions (/home/boehm-s/tmp/node_modules/joi/lib/types/any/index.js:675:31)
at module.exports.internals.Any.root.validate (/home/boehm-s/tmp/node_modules/joi/lib/index.js:138:23)
at Object.<anonymous> (/home/boehm-s/tmp/plop.js:29:17)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
isJoi: true,
name: 'ValidationError',
details: [ [Object] ],
_object: { name: 'name', resource: [Object], fov: 10 },
annotate: [Function] },
value: { name: 'name', resource: { uri: 'file.jpg' }, fov: 10 },
then: [Function: then],
catch: [Function: catch] }
------------------------------
{ error: null,
value: { name: 'name', resource: { uri: 'file.png' }, fov: 10 },
then: [Function: then],
catch: [Function: catch] }
fov
не разрешается, потому что ressource.uri
соответствует регулярному выражению, которое вы предоставили.