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

Intro a Hapi.js [ESP]

Intro a Hapi.js [ESP]

7380658d599187650d426661abe028e7?s=128

Antonio Valverde

May 22, 2014
Tweet

Transcript

  1. intro a hapi.js @valgreens

  2. “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
  3. http://twitter.com/eranhammer/status/406300408647139328

  4. http://twitter.com/eranhammer/status/406283267952738304 http://gist.github.com/hueniverse/7686452

  5. https://twitter.com/eranhammer/status/406249774094876672

  6. $ mkdir app $ cd app/ $ npm init $

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

    “localhost"); ! server.start(function() { console.log(“Hapi server: " + server.info.uri); }); creando el servidor…
  8. server.route({ path: "/", method: "GET", handler: function(request, reply) { reply("Hello,

    world!"); } }); routing…
  9. 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()
  10. 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"}
  11. $ npm install joi --save validación… var Joi = require(‘joi);

  12. 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") } } };
  13. server.route({ path: "/hello/{name*2}", method: "GET", config: helloConfig });

  14. $ 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/
  15. 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 }); }); }
  16. 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 } };
  17. 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 });
  18. server.route({ path: "/static/{path*}", method: "GET", handler: { directory: { path:

    "./public", listing: false, index: false } } });
  19. 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 || "") + ")"); });
  20. 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); } });
  21. 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); }); });
  22. $ mkdir -p plugins/example $ cd plugins/example/ $ npm init

    var internals = {}; ! exports.register = function(plugin, options, next) { next(); };
  23. 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); }); });
  24. 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); }); });
  25. 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."); }); });
  26. 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"); }); });
  27. 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
  28. gracias :)