Introducción a Hapi.js
2014-10-22, Medellín - Colombia
Hapi es un framework HTTP para Node.js centrado en configuración, desarrollado por Walmart Labs, para alimentar su plataforma de backend móvil. Recientemente ha ganado un montón de tracción en la comunidad con más y más compañías empezando a hacer uso de el, compañías tales como PayPal, Beats Audio y Mozilla.
npm init
npm install hapi --save
La instalación de Hapi.js es muy sencilla, y la hacemos a través de NPM de la siguiente manera:
Desarrollar con Hapi.js es realmente sencillo y genera felicidad desde el principio: (si no es así para ti, por favor consulta un siquiatra).
var Hapi = require('hapi');
// Create a server with a host and port
var server = new Hapi.Server('localhost', 8000);
// Add the route
server.route({
method: 'GET',
path: '/hello',
handler: function (request, reply) {
reply('hello world');
}
});
// Start the server
server.start();
var Hapi = require('hapi');
// Create a server with a host and port
var server = new Hapi.Server('localhost', 8000);
// Add the route
server.route({
method: 'GET',
path: '/hello',
handler: function (request, reply) {
reply('hello world');
}
});
server.route({
method: 'POST',
path: '/yolo',
handler: function (request, reply) {
var sampleInfo = {
author: 'Adron Hall',
book: 'Marxist Capitalist Communist Manifesto',
test: "There's a lot in this book!"
};
reply(sampleInfo);
}
});
// Start the server
server.start();
curl -X POST http://localhost:8000/yolo
Routing allows the server to react differently based on the HTTP path requested and method used. Hapi exposes routing at the highest level, without tangled, complex regular expressions.
server.route({
path: "/",
method: "GET",
handler: function(request, reply) {
reply("Hello, world!");
}
});
path: Hapi allows us to define routes to match HTTP paths that are in compliance with the RFC 3986 specification. In addition, Hapi’s router provides parameterized paths, allowing us to extract segments of a path.
Here are some examples of valid values for the path key in the route object.
/my/path => will match requests to http://example.com/my/path and nothing else.
/my/{desc}/path => will match requests to http://example.com/my/test/path, with “test” becoming available to the handler function.
/my/{name*2}/path => will match requests to http://example.com/my/super/awesome/path, with the value of request.params.name being “super/awesome”. The route is matched only if there are two path segments before “/path”.
method: The method key of the route object defines what HTTP method that route deals with, be it GET, POST, PUT, DELETE or PATCH. The method can also be specified as an asterisk (*), signifying that the route will match any method.
handler: The handler key is an object or function that specifies the action to be taken when a request matches the route. More often than not, the handler will be a function with the signature function(request, reply) {…}.
server.route({
path: "/hello/{name*2}",
method: "GET",
handler: function(request, reply) {
var names = request.params.name.split("/");
reply({
first: names[0],
last: names[1],
mood: request.query.mood || "neutral"
});
}
});
It’s often desirable to validate data passed to the route, especially so whilst building an API. Hapi makes this a breeze by using the Joi object schema validation module.
npm install joi@4.x --save
To begin using Joi validation, we need to require the module. Add the following line after we require Hapi.
var Joi = require("joi");
var helloConfig = {
handler: function(request, reply) {
var names = request.params.name.split("/");
reply({
first: names[0],
last: names[1],
mood: request.query.mood
});
},
validate: {
params: {
name: Joi.string().min(8).max(100)
},
query: {
mood: Joi.string().valid(["neutral","happy","sad"]).default("neutral")
}
}
};
server.route({
path: "/hello/{name*2}",
method: "GET",
config: helloConfig
});