JSON Schema
anonimusprogramus opened this issue · 2 comments
Hi Sebastian.
I like v8n, simple and light. I'm trying to use v8n with Fastify framework upon request validation.
How to make v8n outputs a JSON Schema compatible object?
As explained here, but I'd like to use v8n instead of Joi.
Thanks a lot.
Hello @anonimusprogramus, thanks for your question.
I don't know the Fastify framework very well, so maybe this solution is not gonna work as you expect. But as I was looking at the documentation, I ended up with something like this:
function validate(schema, value) {
const [error] = schema.testAll(value);
return error ? { error } : { value };
}
fastify.post('/the/url', {
schema: v8n().schema({
body: v8n().schema({
hello: v8n().string()
})
}),
schemaCompiler: schema => data => validate(schema, data)
}, handler)
The validate
function is a kind of adapter to the Fastify expected interface. I did it very simple in this example (with destructuring syntax), but you can use your imagination to create custom messages by using the v8n ValidationError returned by testAll
. 🙂
Bruno, thanks for your reply, much apreciated.
I've been trying your suggestion and some varians but still no luck, perhaps I need to read again v8n, fastify and json schema again. Hope there's something I missed. And this issue won't stop me from using v8n, it's awesome!
Again, thank you very much.