Make me Hapi

Introducción a Hapi.js

2014-10-22, Medellín - Colombia

The Pursuit of Hapi-ness

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.

Características

  • Strength: Simple, clean design. Performance.
  • Weakness: Not as many plugins and communities available as some of the competing frameworks.
  • Great for: Building sites and APIs with a focus on clean code and performance.

Instalación

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:

Because I'm Hapi

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();

A little more hapi-ness

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();

Routing

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!");
    }
});

Routing

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”.

Routing

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) {…}.

Putting It All Together

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"
        });
    }
});

Validation

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
});
Made with Slides.com