korzio / djv

Dynamic JSON Schema Validator - Supports draft-04/06
https://www.npmjs.com/package/djv
MIT License
289 stars 31 forks source link

Explain example #53

Closed Zyles closed 7 years ago

Zyles commented 7 years ago

I don't understand the example in the readme after trying for an hour or so

Using an example from the JSON schema docs:

http://json-schema.org/example1.html

        const env = new Djv({ version: 'draft-06' })
        const jsonSchema = {
          '$schema': 'http://json-schema.org/draft-06/schema#',
          'title': 'Product',
          'description': 'A product from Acme\'s catalog',
          'type': 'object',
          'properties': {
            'id': {
              'description': 'The unique identifier for a product',
              'type': 'integer'
            },
            'name': {
              'description': 'Name of the product',
              'type': 'string'
            },
            'price': {
              'type': 'number',
              'exclusiveMinimum': 0
            }
          },
          'required': ['id', 'name', 'price']
        }

        const product = {
          'id': 'asdf', // Should be number
          'name': 'A green door',
          'price': 12.50
        }

        // Use `addSchema` to add json schema
        env.addSchema('test', jsonSchema)

        console.log(env.validate('test', product))

Outputs: type: data['id']

This error message makes no sense to me. What is it telling me? How do I parse this so I can show an error message?

It would be better to say "property id is invalid" or whatever. Or return an object with the invalid fields.

{'errors': {
'id': { 'message': 'Field is invalid' }
}}
Zyles commented 7 years ago

Looking closer I see that I maybe should use the errorhandler, but I have a hard time figuring out how.

The example gives me console error:

SyntaxError: Unexpected identifier

For this line:

data: '${this.data[this.data.length - 1]}'

korzio commented 7 years ago

@Zyles Yes, the error messages currently have the simpliest output as possible. However there is a way to customize them in any customer way. Also there are some stories regarding error handling planned for the future work https://github.com/korzio/djv/issues/54

korzio commented 7 years ago

@Zyles I've added your example to the project tests list. I've updated to main documentation for setErrorHandler as well (it was throwing an error if just copy it) Here is a simple handler sample. However it is quite flexible, still the custom handling should be updated, and that work is already planned for the future minor release.

korzio commented 7 years ago

Here is a PR - https://github.com/korzio/djv/pull/59