hapi
A restful api server that separates your business logic from the server gears so you can focus on coding stuff.
Basic Usage
var hapi = require('hapi');
var server = new hapi.Server.Server('localhost', 8088, {name:'sample', uri:'0.0.0.0'});
function sampleGet(hapi, reply) {
reply('hello world');
}
server.addRoute({
path : '/sample',
method : 'GET',
handler : sampleGet,
authentication: 'none'
});
server.start();
Now navigate to http://localhost:8080/sample and you should receive 'hello world'
Routes
Configuration options
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
-
Wildcards
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.
server.addRoute({
path : '/luna/:album',
method : 'GET',
handler : albumRetrieve,
authentication: 'none'
});
function albumRetrieve(hapi, reply) {
console.log(hapi.params.album);
reply(albumGet(hapi.params.album));
}
Handlers
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
Middleware
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}});
Utils
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 to to
with subject
and content of text
or html
calling callback(err)
when finishedencrypt(key, value)
- encrypts value with AES Symmetric encryptiongetTimeStamp()
- gives a 'now' timestampgetRandomString(size)
- returns a random string of size
hide(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