Objection.js: Json Schema Custom Formats

Created on 30 Sep 2016  路  7Comments  路  Source: Vincit/objection.js

This is a feature request to add custom format definitions for the JSON Schema validation performed by Ajv. It makes it much easier to insert custom validations on per-field basis while still making use of the JSON Schema. I could do this by overriding $validate, but it would basically require me to redo all the work Objection is already doing, which seems like waste.

With tv4 I could do this by importing tv4 into my own library and adding them there, but Ajv doesn't have a way to statically add formats, so I would need access to the instance. The easiest way would be to store the ajv instance on ModelBase, but that is probably weird from an API standpoint. It would also be trivial to add a addSchemaFormat or addCustomValidator function to ModelBase that looks like

// I'm used to TypeScript, so that's how I'm going to annotate this, I hope that's clear.
addCustomValidator(name: string, validator: (value: any) => boolean): void {
  ajv.addFormat(name, validator);
} 

This could reasonably well separate your api from theirs so if you change schema validators again this function can be adjusted, unless you switched to one that doesn't handle custom formats at all.

I understand if you reject this outright, since it's already possible. I only suggest it because it's a very simple change that your underlying tools already support. And my way of doing this would likely look just like what you're already doing, just so I have access to the ajv variable, which seems like overkill.

Edit

I somehow managed to submit this before I was done writing it, so I closed it and finish before re-opening, sorry about that.

enhancement

Most helpful comment

Implemented in 0.7.0-rc.1. Check out this for how to modify ajv.

All 7 comments

Sounds like a good idea. I'll add some way to add custom validators. Your suggestion seems good, but I'll give this some thought first.

I would love for this so to make the cut in a future 0.7. Currently, adding custom keyword validations is a hassle because of multiple instancing of ajv. For my use case, objection.ajv() (to mimic objection.knex()) would suffice.

I'm going to of add this before 0.7 in one of the patch versions of 0.6.

@fl0w objection.ajv() would marry objection with ajv. Maybe a more generic interface like the one @Cody157 suggested would be enough? @fl0w If you are still looking for something to do, would you like to take this on?

Sure I'll grab it.

Implemented in 0.7.0-rc.1. Check out this for how to modify ajv.

Was this page helpful?
0 / 5 - 0 ratings