0

I want to validate multiple occurrences of the same query parameter using AJV.

My OpenApi schema looks something like this:

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

I convert it to a valid json schema to be able to validate it with AJV:

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

Naturally, AJV validation works fine for one parameter of type integer.

I want to be able to validate multiple occurrences of user_id. For example: /contacts?user_id=1&user_id=2 is converted to { user_id: [1, 2] } and I want it to actually be valid.

At this point validation fails because it expects an integer but received an array. Is there any way to validate each items of the array independently ?

Thanks

Aurelien
  • 339
  • 3
  • 12
  • Related (or duplicate): [How to pass multi value query params in Swagger](https://stackoverflow.com/q/47420755/113116), [Swagger UI not sending array correctly](https://stackoverflow.com/questions/36329771/swagger-ui-not-sending-array-correctly) – Helen Nov 05 '18 at 15:44

1 Answers1

0

Perhaps the schema for user_id should use the anyOf compound keywords allowing you to define multiple schemas for a single property:

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>
customcommander
  • 17,580
  • 5
  • 58
  • 84