如何解决JOI验证对来自给定对象数组的对象是否有效
我的请求正文包含一个Javascript / JSON对象:
{ id: 1,value: "example 1"}
我有一个允许的对象列表:
[
{ id: 1,value: "example 1" },{ id: 2,value: "example 2" },{ id: 3,value: "example 3" },]
我正在编写Joi schema,并希望验证请求正文中的对象是否在我的允许值列表中。
解决方法
您需要使用Joi的arrayOfPromises
属性:https://joi.dev/api/?v=17.2.1#anycustommethod-description。您将需要一个类似
any.custom()
您应该可以使用以下代码:
const _ = require('lodash');
const allowed = [
{ id: 1,value: 'value 1' },...
{ id: 9,value: 'value 9' },];
function isOneOf(allowedValues) {
return (v,helpers) => {
if ( ! _.some(allowedValues,x => _.isEqual(x,v) ) {
return helpers.error('naughty!');
}
};
}
,
我假设数组中的ID是唯一的
yourObj = {id:1,value: "example 1"};
yourArray = [{id:1,value: "example 1"},{id:2,value: "example 2"},{id:3,value: "example 3"}]
isObjectAvailable = yourArray.some(el=>el.id===yourObj.id)
console.log(isObjectAvailable) // return true if found else false
,
假设您希望您的架构验证此对象数组。
const example = {
"id": 1,"value": "example1"
};
Joi模式应为
var validator = require('@hapi/joi');
const rules = validator.object().keys({
id: validator.number().required(),value: validator.string().required()
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。