【问题标题】:Validate multiple occurrences of query parameters using json-schema and AJV使用 json-schema 和 AJV 验证查询参数的多次出现
【发布时间】:2019-04-08 00:52:32
【问题描述】:

我想使用 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] },我希望它实际上是有效的。

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

谢谢

【问题讨论】:

标签: node.js jsonschema openapi ajv


【解决方案1】:

也许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>

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2016-08-23
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2019-04-03
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多