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.
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!
Most helpful comment
Hi,
Objection uses ajv as the json schema validator. You can enable the
coerceTypesoption.This is how you can override ajv options:
Let me know if this works