Objection.js: JSON Schema Type Conversion / Coercion

Created on 15 Aug 2019  路  2Comments  路  Source: Vincit/objection.js

Hi there. I've been looking through the docs & existing issues but am having a hard time finding information about this.

Is there a standard way to handle type coercion with JSON Schema?

For instance, I have a select input with integer values but by simple virtue of being a select input the values will always be strings. In my DB, however, they need to be integers. If I try to input this data get a ValidationError. Checking every place some front end JavaScript messes with a type would be rather cumbersome.

Most general way I have found so far is to define a $parseJson on a BaseModel, look for keys that should be numbers, and make a conversion there. Is the generally The Way or is there a more built in approach to this? If there isn't would you _want_ a built in approach?

Thanks for reading.

Most helpful comment

Hi,

Objection uses ajv as the json schema validator. You can enable the coerceTypes option.

This is how you can override ajv options:

class BaseModel extends Model {
  static createValidator() {
    return new AjvValidator({
      onCreateAjv: ajv => {},
      options: {
        allErrors: true,
        validateSchema: false,
        ownProperties: true,
        v5: true,
        coerceTypes: true // <--- !!!
      }
    });
  }
}
const { BaseModel } = require('./base-model')

class Person extends BaseModel {
  ...
}

Let me know if this works

All 2 comments

Hi,

Objection uses ajv as the json schema validator. You can enable the coerceTypes option.

This is how you can override ajv options:

class BaseModel extends Model {
  static createValidator() {
    return new AjvValidator({
      onCreateAjv: ajv => {},
      options: {
        allErrors: true,
        validateSchema: false,
        ownProperties: true,
        v5: true,
        coerceTypes: true // <--- !!!
      }
    });
  }
}
const { BaseModel } = require('./base-model')

class Person extends BaseModel {
  ...
}

Let me know if this works

That works fantastically, thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ahlid picture Ahlid  路  3Comments

nazar picture nazar  路  3Comments

purepear picture purepear  路  3Comments

sgangwisch picture sgangwisch  路  4Comments

louis-etne picture louis-etne  路  4Comments