Intro a Hapi.js [ESP]

Intro a Hapi.js [ESP]

Antonio Valverde

May 22, 2014

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

28 slides
  1. “A rich framework for building web applications and services. hapi

    is a simple to use configuration-centric framework with built-in support for input validation, caching, authentication, and other essential facilities. hapi enables developers to focus on writing reusable application logic instead of spending time building infrastructure. The framework supports a powerful plugin architecture for pain-free and scalable extensibility.” http://spumko.github.io
  2. $ mkdir app $ cd app/ $ npm init $

    npm install hapi --save para empezar…
  3. var Hapi = require(“hapi"); ! var server = new Hapi.Server(8080,

    “localhost"); ! server.start(function() { console.log(“Hapi server: " + server.info.uri); }); creando el servidor…
  4. path * ‘mi/ruta’: localhost/mi/ruta * ‘mi/{adj}/ruta’: localhost/mi/gran/ruta o localhost/mi/peor/ ruta

    (request.params.adj) GET, POST, PUT, DELETE, PATCH o (*) method handler * request.params, request.query, request.payload, request.headers * reply es la interfaz para devolver una respuesta al servidor * puedes enviar: String, Object/Array, Buffer, ReadableStream * reply.file(), reply.view(), reply.close() y reply.proxy()
  5. server.route({ path: "/hola/{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" }); } }); http://localhost:8080/hola/Walter/White?mood=happy {"first":"Walter","last":"White":"mood":"happy"}
  6. 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") } } };
  7. $ npm install catbox-redis --save caching… var server = new

    Hapi.Server(8080, "localhost", { cache: { engine: "catbox-redis", options: { host: "localhost", partition: "app", password: "mypass" } } }); http://github.com/spumko/catbox/
  8. server.method("getColour", function(name, next) { var colours = ["red", "blue", “yellow",

    "green"]; var colour = colours[Math.floor(Math.random() * colours.length)]; next(null, colour); }, { cache: { expiresIn: 30000 } }); function(request, reply) { var names = request.params.name.split("/"); server.methods.getColour(request.params.name, function(err, colour) { reply({ first: names[0], last: names[1], mood: request.query.mood, colour: colour }); }); }
  9. var helloConfig = { handler: function(request, reply) { var names

    = request.params.name.split(“/"); var colours = ["red", "blue", “yellow", "green"]; var colour = colours[Math.floor(Math.random() * colours.length)]; reply({ first: names[0], last: names[1], mood: request.query.mood, color: colour }); }, cache: { expiresIn: 60000 } };
  10. vistas y estáticos… views: { engines: { jade: "jade" },

    path: "./views" } reply.view("hello", { first: names[0], last: names[1], mood: request.query.mood, colour: colour });
  11. logging… server.log(["test"], "This is my log entry!"); server.log(["error"], "Bogus data

    received from cache, unable to proceed."); server.on("log", function(event, tags) { var tagsJoined = Object.keys(tags).join(); var message = event.data; console.log("Log entry [" + tagsJoined + "] (" + (message || "") + ")"); });
  12. server.route({ path: "/log/{data}", method: "GET", handler: function(request, reply) { request.log(["pathData"]);

    reply("Logged " + request.params.data); } }); server.on("request", function(request, event, tags) { if (tags.pathData) { console.log("Logging pathData: " + request.params.data); } });
  13. plugins… $ npm install lout --save server.pack.require("lout", function(err) { if

    (err) throw err; server.start(function() { console.log("Hapi server: ”+server.info.uri); }); });
  14. $ mkdir -p plugins/example $ cd plugins/example/ $ npm init

    var internals = {}; ! exports.register = function(plugin, options, next) { next(); };
  15. var internals = {}; exports.register = function(plugin, options, next) {

    plugin.route({ path: "/mi/plugin", method: "GET", handler: function(request, reply) { reply(“Hola desde un plugin"); } }); next(); }; server.pack.require(["lout", "./plugins/example"], function(err) { if (err) throw err; server.start(function() { console.log("Hapi server: "+server.info.uri); }); });
  16. server.pack.require({ "lout": {}, "./plugins/example": { // objeto con opciones }

    }, function(err) { if (err) throw err; server.start(function() { console.log("Hapi server: "+server.info.uri); }); });
  17. packs… var pack = new Hapi.Pack(); var s1 = pack.server(8080,

    "localhost"); s1.route({ path: "/server/{id}", method: "GET", handler: function(request, reply) { reply(request.params.id); } }); var s2 = pack.server(8081, "localhost"); pack.require(["lout", "./plugins/example"], function(err) { if (err) throw err; pack.start(function(server) { console.log("Hapi pack started."); }); });
  18. composer… var manifest = { servers: [ {port: 8080}, {port:

    8081} ], plugins: ["lout", "./plugins/example"] } var composer = new Hapi.Composer(manifest); ! composer.compose(function() { composer.start(function() { console.log("Servers started"); }); });
  19. enlaces de interés… * Variables de entorno y hapi: http://vawks.com/blog/

    2014/03/18/hapi-confidence/ * API Reference: http://github.com/spumko/hapi/blob/master/ docs/Reference.md * Repositorios de la suite: http://github.com/spumko * Podcast en el que hablan de #nodebf y como usan node en Walmart: http://nodeup.com/fiftysix

More Decks by Antonio Valverde

Other Decks in Programming