I'm trying to write a Joi validation for a JSON object coming into a Hapi handler. So far the code looks like this:
server.route({
method: 'POST',
path: '/converge',
handler: function (request, reply) {
consociator.consociate(request.payload)
.then (function (result) {
reply (200, result);
});
},
config: {
validate: {
payload: {
value: Joi.object().required().keys({ knownid: Joi.object() })
}
}
}
});
You can see the Joi object validation so far in the config: validate: code section above. The JSON coming in looks like this.
"key": '06e5140d-fa4e-4758-8d9d-e707bd19880d-testA',
"value": {
"ids_lot_args": {
"this_id": "stuff",
"otherThign": "more data"
},
"peripheral_data": 'Sample peripheral data of any sort'
}
In this JSON above the key and value at the root of the object are required, and the section called ids_lot_args
is required. The section that starts with peripheral_data could be there or not, or could be any other JSON payload. It doesn't matter, only key and value at the root level and ids_lot_args
inside the value are required.
So far, I'm stumbling through trying to get the Joi validation to work. Any ideas on how this should be setup? The code repo for Joi is located at https://github.com/hapijs/joi if one wants to check it out. I've been trying the allow all functions on objects to no avail so far.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.
You just need to call the unknown()
function on the value
object:
var schema = Joi.object({
key: Joi.string().required(),
value: Joi.object({
ids_lot_args: Joi.object().required()
}).unknown().required()
});
You can use the "allowUnknown" parameter:
validate : {
options : {
allowUnknown: true
},
headers : {
...
},
params : {
...
},
payload : {
...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With