Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created February 26, 2016 21:07
Show Gist options
  • Save kevboutin/43125263b3a96de15825 to your computer and use it in GitHub Desktop.
Save kevboutin/43125263b3a96de15825 to your computer and use it in GitHub Desktop.
Shows how to use joi for request validation when using hapi within Node.js.
'use strict';
const Hapi = require('hapi');
const Joi = require('joi');
const server = new Hapi.Server();
server.connection({ port: 8000 });
// test by calling:
// http POST localhost:8000/user/123?id=456
// or for validation failure testing, call:
// http POST localhost:8000/user/123?id=foo
server.route({
method: ['POST', 'PUT'],
path: '/user/{id?}', //id is set to optional with the ?
config: {
validate: {
params: Joi.object({
id: Joi.number()
}),
query: Joi.object({
id: Joi.number()
})
},
handler: function(request, response) {
response({
params: request.params,
query: request.query,
payload: request.payload
});
}
}
});
server.start(() => console.log(`Started at ${server.info.uri}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment