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()
    })