jsen icon indicating copy to clipboard operation
jsen copied to clipboard

Better support for oneOf / anyOf

Open otakustay opened this issue 8 years ago • 0 comments

Currently jsen validation against oneOf or anyOf schema reports quite unreadable errors, suppose we have test code like:

let jsen = require('jsen');

let schema = {
    oneOf: [
        {
            type: 'object',
            properties: {
                id: {
                    type: 'number'
                },
                name: {
                    type: 'string',
                    minLength: 1
                }
            },
            required: ['id', 'name']
        },
        {
            type: 'object',
            properties: {
                id: {
                    type: 'number'
                },
                value: {
                    type: 'string',
                    minLength: 1
                }
            },
            required: ['id', 'value']
        }
    ]
};

let input = {
    id: null,
    name: ''
};

let validate = jsen(schema);
let isValid = validate(input);
console.log('isValid', isValid);
console.log(validate.errors);

The output would be:

isValid false
[ { path: 'id', keyword: 'type' },
  { path: 'name', keyword: 'minLength' },
  { path: 'id', keyword: 'type' },
  { path: 'value', keyword: 'required' },
  { path: '', keyword: 'oneOf' } ]

The problem is from the path reported we don't know exactly the relationship of error and schema

jsonschemavalidator has a more decent schema path in error object which contains the index within oneOf or anyOf and have a parent-child relationship for errors:

Message: JSON is valid against no schemas from 'oneOf'.
Schema path: #/oneOf
    -- These are children errors --
    Message: Invalid type. Expected Number but got Null.
    Schema path:  #/oneOf/1/properties/id/type
    Message: Invalid type. Expected Number but got Null.
    Schema path: #/oneOf/0/properties/id/type
    Message: String '' is less than minimum length of 1.
    Schema path: #/oneOf/0/properties/name/minLength
    Message: Required properties are missing from object: value.
    Schema path: #/oneOf/1/required

It's much more convenient for detecting and displaying error messages

otakustay avatar Mar 20 '17 06:03 otakustay