Hapi.js - intro

project hapi background

Fully open source from 1st day - 05.08.2011, WalmartLabs

Designed and created for Walmart-scale

Full-time, dedicated team and plugins maintainers - community

Battled in high-traffic applications

Always 100% code coverage

why hapi ?

Configuration centric framework

Built in validation, authentication, caching and more

Tailored towards more complex applications but simple code

Optional plugins and modules

Native node constructs used happily (streams, buffers, ..)

configuration centric

server.route({
    method: 'GET',
    path: '/v1/incidents',
    handler: getIncidents,
    config: {
        // Setting Cache-Control header
        cache: {
            expiresIn: 30 * 1000,
            privacy: 'private'
        }
    }
});

server.route({
    method: 'PATCH',
    path: '/v1/incidents/{id}',
    handler: updateIncident,
    config: {
        // Validating request parameters and payload
        validate: {
            params: {
                id: Joi.number().integer().min(1)
            },
            payload: Joi.object({
                elapsed: Joi.number().integer().min(0),
                elapsedPlus: Joi.number().integer().min(0),
                text: Joi.string().max(2048).allow(''),
                sortOrder: Joi.number().integer().min(0)
            }).or('elapsed', 'elapsedPlus', 'text', 'sortOrder')
        }
    }
});

server.route({
    method: 'DELETE',
    // Path manipulation
    path: '/v1/incidents/{id}/{otherParams?}',
    handler: deleteIncident
});

custom Plugins

Creating a plugin:

function myRandomKittyPlugin(server, options, next) {
    // Adding routes, server methods, hooks to lifecycle events
    next();
};

myRandomKittyPlugin.attributes = {
    name: 'MyRandomKittyPlugin'
};

module.exports = {
    register: myRandomKittyPlugin
};

Loading a plugin:

server.register(require('my-random-kitty-plugin'), err => {
    if (err) {
        console.error('Failed to load plugin:', err);
    }
});

modules from hapijs

MOOORE...

community and resources

HapiDay Oakland 2014

Copy of Hapi-intro

By tkssharma

Copy of Hapi-intro

  • 1,122