Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to hapi

Introduction to hapi

Slides from Javascript-Meetup (01. Sep 2014) in Stuttgart

Kentaro Wakayama

September 01, 2014
Tweet

Other Decks in Programming

Transcript

  1. Ge#ng&Started var hapi = require('hapi'), server = new hapi.Server('localhost', 8000);

    server.start(function() { console.log('hapi server started @ ' + server.info.uri); });
  2. Rou$ng server.route({ method: 'GET', path: '/hello/{name*2}', handler: function(request, reply) {

    reply('hello ' + request.params.name + '. Nice to see you!'); } });
  3. Caching server.method('getProfile', function(id, next) { next(null, { 'id': id, 'timestamp':

    new Date }); }, { cache: { expiresIn: 10000 } }); server.route({ method: 'GET', path: '/profile/{id}', handler: function(request, reply) { server.methods.getProfile(request.params.id, reply); } });
  4. Valida&on)with)Joi server.route({ method: 'GET', path: '/hello/{name}', handler: function(request, reply) {

    reply('hello ' + request.params.name + '. Nice to see you!'); }, config: { validate: { params: { name: joi.string().required().min(3).max(10) } } } });
  5. Plugins()(Modular(Concept var hapi = require('hapi'); hapiSwagger = require('hapi-swagger'); var server

    = new hapi.Server('localhost', 8000); server.pack.register(hapiSwagger, function(err) { if (err) throw err; server.start(function() { console.log('hapi server started @ ' + server.info.uri); }); });
  6. Plugins()(Basic(structure exports.register = function (plugin, options, next) { plugin.route({ method:

    'GET', path: '/stuttgartjs', handler: function (request, reply) { reply('pizza and beer!'); } }); next(); }; exports.register.attributes = { pkg: require('./package.json'); };
  7. Tes$ng var assert = require('assert'), hapi = require('hapi'), plugin =

    require('../'); describe('Test Plugin', function() { var server; beforeEach(function(){ server = new hapi.Server(); }); it('loads successfully', function(done) { server.pack.register(plugin, function(err) { assert.ok(!err); done(); }); }); it('responses to GET request on /', function(done) { var request = { method: 'GET', url: '/' }; server.pack.register(plugin, function(err) { server.inject(request, function(res) { assert.equal(res.statusCode, 200); assert.equal(res.result, 'don\'t worry, be hapi!'); done(); }); }); }); });
  8. Composer var manifest = { servers: [ { port: 8080

    }, { port: 8081 } ], plugins: { "hapi-swagger": {} "./plugins/example": { endPoint: "/my/custom/route" } } }; hapi.Pack.compose(manifest, function(err, pack) { pack.start(function() { console.log('Servers started'); }); });
  9. Composer(commandline manifest.json,+,package.json { "servers": [{ "port": 8080 }, { "port":

    8081 }], "plugins": { "hapi-swagger": {}, "stuttgartjs": {} } } Use$hapi$globally hapi -c manifest.json