0

我想使用 AJV 验证相同查询参数的多次出现。

我的 OpenApi 架构如下所示:

...
/contacts:
  get:
    parameters:
      - name: user_id
        in: query
        schema:
          type: integer
...

我将其转换为有效的 json 模式,以便能够使用 AJV 对其进行验证:

{
  query: {
    properties: {
      user_id: { type: 'integer' }
    }
  }
}

自然地,AJV 验证适用于整数类型的一个参数。

我希望能够验证多次出现的user_id. 例如:/contacts?user_id=1&user_id=2被转换为{ user_id: [1, 2] }并且我希望它实际上是有效的。

此时验证失败,因为它需要一个整数但接收到一个数组。有没有办法独立验证数组的每个项目?

谢谢

4

1 回答 1

0

也许架构user_id应该使用anyOf复合关键字,允许您为单个属性定义多个架构:

var ajv = new Ajv({
  allErrors: true
});

var schema = {
  "properties": {
    "user_id": {
      "anyOf": [{
          "type": "integer"
        },
        {
          "type": "array",
          "items": {
            "type": "integer"
          }
        },
      ]
    },
  }
};

var validate = ajv.compile(schema);

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

test({
  "user_id": 1
});
test({
  "user_id": "foo"
});
test({
  "user_id": [1, 2]
});
test({
  "user_id": [1, "foo"]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.5.5/ajv.min.js"></script>

于 2018-11-12T22:44:22.260 回答