by akie · 5y ago · 0 comments
Well, I think you just moved the validation code to another place. Instead of putting it in your app, where (in my opinion) it belongs, you are putting it in a hard-to-read and difficult to understand external JSON file. I'm not sure how that's an improvement.
schemaValidate(input, {
"required": ["price"]
"properties": {
"price": {
"type": "number",
"minimum": 0,
"maximum": 1000
}
}})
vs if (input.hasOwnProperty("price"))
throw Error("Missing price property")
let price = parseInt(data["price"], 10)
if (isNaN(price))
throw Error("Property 'price' is not a number")
if (price < 0)
throw Error("Property 'price' is negative")
if (price > 1000)
throw Error("Property 'price' is too high")
Not claiming the later is particularly difficult, in fact it's very easy to understand, but it is sligthly more verbose and tedious, for bigger validations it can become even worse. Here the schema turns every 2-3 lines of custom validation code into 1, provides automatic and better error messages of the error cause and acts as a contract which consumers of the api can read or even use to auto generate code, GUI, autocompletion. For the later use cases you would of course put the schema in a separate public file. For more complex validation you can of course add them after calling schemaValidate.Otherwise, it’s just in your code, where it’s potentially not just “hard-to-read”, but impossible to read for anybody but the authors.
That said, I’m partial to other solutions like protobuf, but what can you do.
Also, I can replicate my validations at many levels down the stack: from the client to API-GW to the database model. All with a single definition.