Created
February 26, 2016 21:07
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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