Joi阵列验证

问题描述

考虑此代码段。我想按1种或多种颜色查询标记” ...

module.exports = [
    {
        method: 'GET',path: '/search/markers',options: {
            auth,description: 'Get Markers',notes: 'Returns all marker info',tags: ['api','markers'],validate: {
                query: {
                    color: Joi.array().items(Joi.string().valid('Red','Blue')).single().allow(''),}
            },response: {
                schema: MarkersValidation.getSearchMarkers
            }
        },handler: SearchController.searchMarkers
    }
];

exports.searchMarkers = async (request,h) => {
    try {
        const Markers = h.models().Markers;
        const queryMarkers = Markers.query()
            .select(h.knex().raw([
                'markers.color'
            ]))
            if (request.query.color) {
                queryMarkers.andWhere(h.knex().raw(`color && '{${request.query.color}}'::text[]`));
            }
        }
    }
    catch (e) {
        //error handler
    }
}

但是,当我尝试同时使用Red,Blue和color的查询参数时,我从Postman收到以下错误。当我应用单个颜色参数时,例如:Red,它可以正常工作。

错误

子项“ color”失败,因为[color的单个值失败,因为[color]必须是[Red,Blue]中的一种]

URL

{{url}} / search / markers?color =红色,蓝色

注意

我尝试删除.single(),但是当我这样做时,出现此错误

子“颜色”失败,因为[“颜色”必须是数组]

问题

我该如何解决

假设我想通过以下方式查询可用颜色的列表:“绿色”,“紫色”,“黄色”,“红色”,“蓝色”。

如何在查询添加1个或所有选项?

示例

{{url}} / search / markers?color = Red

{{url}} / search / markers?color =红色,蓝色,黄色

这是我当前的代码,但是显然不起作用,有什么想法吗?

const myColors = ['Green','Purple','Yellow','Red','Blue'];

validate: {
 query: {
  color: Joi.array().items(Joi.string().valid(myColors)).single().allow(''),}
}

已更新-已简化

在此图中,我有一个带有“ .valid()”的数组,验证失败。

In this image,I have an array with ".valid()" and the validation fails

在此图中,我有一个不带“ .valid()”的数组,并且验证通过。

In this image,I have an array with no ".valid()" and the validation passes

我的问题

如何在我的Joi.array中添加“ .valid()”或类似的内容,以便只有我设置的值对此查询有效?

解决方法

您必须在URL中将颜色查询参数作为数组传递。

{{url}}/search/markers?color[]=Red&color[]=Blue

用于验证颜色数组的joi模式:

const myColors = ['Green','Purple','Yellow','Red','Blue'];

joi.object().keys({
  color: joi.array().items(myColors.map(col => col)),});

,
const myColors = require('../data/colors');

const validateColors = (colors) => {
    if (!colors) {
        return true;
    }
    const colorsArray = colors.split(',');
    const colorsSchema = Joi.array().items(Joi.string().valid(myColors)).allow('')
    return Joi.validate(colorsArray,colorsSchema);
}

query: {colors: Joi.string().allow('')}