A restful api server that separates your business logic from the server gears so you can focus on coding stuff.
var hapi = require('hapi');
//create a server with a host, port, and options
var server = new hapi.Server.Server('localhost', 8088, {name:'sample', uri:'0.0.0.0'});
//define the function that returns our value (could be external to this file)
function sampleGet(hapi, reply) {
reply('hello world');
}
//add the route
server.addRoute({
path : '/sample',
method : 'GET',
handler : sampleGet,
authentication: 'none'
});
//start the server
server.start();Now navigate to http://localhost:8080/sample and you should receive 'hello world'
path- endpoint (see Director for endpoint matching patterns )method- http method for routing endpointhandler- Function to handle requestauthentication- Type of authenticationtos- Terms of Service required for that requestquery-schema-scope-
Wildcard declaration in routes are handled the same way as they are in Director or Express. Their retrieval on the handler is handled a little differently.
//when you add a route like this:
server.addRoute({
path : '/luna/:album',
method : 'GET',
handler : albumRetrieve,
authentication: 'none'
});
function albumRetrieve(hapi, reply) {
//hapi.params will have the parameter
console.log(hapi.params.album);
reply(albumGet(hapi.params.album));
}Each handler needs two parameters, usually named 'hapi' and 'reply'.
hapi- the first parameter. provides request informationreply- function to call that takes a json body as a response
hapi provides a few places where middleware can be added into the functions being called for each request. They are:
onPreRoute- gets called before the request is routed.onPreHandler- gets called after the request has been routed before the assigned handler is calledonPostHandler- gets called after the request headersonPostRoute- called after all the routes have been matched
Add them via the 'ext' portion of the options.
var server = new hapi.Server.Server('localhost', 8088, {name:'sample', uri:'0.0.0.0', ext: {onPreRoute:myPreRouteFunction}});hapi provides a myriad of util functions for your use
abort(message)- logs message to console and exits the process.checkEmail(email)- checks for a valid email addressclone(obj)- clones an object or arraydecrypt(key, value)- decrypts value with AES Symmetric encriptionemail(to, subject, text, html, callback)- sends an email totowithsubjectand content oftextorhtmlcallingcallback(err)when finishedencrypt(key, value)- encrypts value with AES Symmetric encryptiongetTimeStamp()- gives a 'now' timestampgetRandomString(size)- returns a random string ofsizehide(object, definition)- removes hidden keysmap(array, key)- turns an array into an objectmerge(target, source)- Merge all the properties of source into target; source wins in conflictunique(array, key)- removes duplicates from an array