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

Building Web APIs with Hapi.js and MongoDB (Mongoose)

Building Web APIs with Hapi.js and MongoDB (Mongoose)

Daf1617c9a4ff129239e922e8c56af1b?s=128

Donn Felker

April 02, 2014
Tweet

Transcript

  1. HTTP WEB API w/ nodejs & mongodb build a

  2. tweet tweet @donnfelker

  3. speakerdeck.com/donnfelker/

  4. github.com/donnfelker/hapi-mongodb-example

  5. topics nodejs hapi mongoose mongodb

  6. beginner | intermediate (know some javascript and understand callbacks and

    ‘sorta’ grok mongodb)
  7. what is ?

  8. Node.js is a platform built on Chrome's JavaScript runtime for

    easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. -nodejs.org
  9. standing on the shoulders of giants

  10. hosting | paas

  11. how do I build a web api with nodejs?

  12. basic tools blank slate start with vanilla nodejs

  13. that’s raw. lets use some tools.

  14. hapi server framework for node.js expressjs.com

  15. hapijs.com | walmart labs

  16. var  Hapi  =  require('hapi');

  17. var  Hapi  =  require('hapi'); var  server  =  new  Hapi.Server('localhost',  8000);

  18. var  Hapi  =  require('hapi'); var  server  =  new  Hapi.Server('localhost',  8000);

    var  handler  =  function(request,  reply)  {   reply({  message:  "Hello  from  Hapi.js!"}); };
  19. var  Hapi  =  require('hapi'); var  server  =  new  Hapi.Server('localhost',  8000);

    var  handler  =  function(request,  reply)  {   reply({  name:  "Ian"}); }; server.route({   method:  'GET',   path:  '/user',   handler:  handler });
  20. var  Hapi  =  require('hapi'); var  server  =  new  Hapi.Server('localhost',  8000);

    var  handler  =  function(request,  reply)  {   reply({  name:  "Ian"}); }; server.route({   method:  'GET',   path:  '/user',   handler:  handler }); server.start(function  ()  {        console.log('Server  started  at:  '  +  server.info.uri); });
  21. var  Hapi  =  require('hapi'); var  server  =  new  Hapi.Server('localhost',  8000);

    var  handler  =  function(request,  reply)  {   reply({  name:  "Ian"}); }; server.route({   method:  'GET',   path:  '/user',   handler:  handler }); server.start(function  ()  {        console.log('Server  started  at:  '  +  server.info.uri); });
  22. server.route({   method:  'GET',   path:  '/user',   config:  userHandler

    });
  23. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,     cache:  {       expiresIn:  5  *  60  *  1000,     }   } });
  24. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,     cache:  {       expiresIn:  5  *  60  *  1000, staleIn:  4  *  60  *  1000, staleTimeout:  200     }   } });
  25. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,  validate:  {      query:  {          id:  Joi.number()  }  }   } });
  26. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,  validate:  {      query:  {          id:  Joi.number().min(100).required()  }  }   } });
  27. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,  validate:  {      query:  {          id:  Joi.number().min(100).required(),          username:  Joi.string().alphanum().min(3).max(20)  }  }   } });
  28. server.route({   method:  'GET',   path:  '/user',   config:  {

        handler:  rootHandler,  validate:  {      query:  {          id:  Joi.number().min(100).required().xor(‘username’),          username:  Joi.string().alphanum().min(3).max(20)  }  }   } });
  29. hapi.js is configuration-centric easy to learn.

  30. persistence

  31. what is mongoDB ?

  32. MongoDB (from "humongous") is a scalable, high- performance, open source

    NoSQL database. - mongodb.org
  33. records are stored known as ‘documents’ and resemble json {

      "source"  :  "127.0.0.1",   "action"  :  "testAction",   "category"  :  "testCategory",   "_id"  :  ObjectId("532deb3d1d4b597d8bfbd270"),   "dateCreated"  :  ISODate("2014-­‐03-­‐22T19:57:49.062Z"), }
  34. hapi nodejs mongoose mongodb

  35. var mongoose = require('mongoose'); var db = mongoose.createConnection('localhost', 'felkerlytics'); var

    schema = mongoose.Schema({ action: 'string', category: 'string' }); // ... etc var AnalyticEvent = db.model('analytic_event', schema); var analyticEvent = new AnalyticEvent({ action: 'linkClick' }); analyticEvent.save(function (err) { if (err) // ... reply(Boom.wrap(err)); }); mongoose mongoosejs.com
  36. the analytic event model var  Mongoose      =  require('mongoose');

    var  Schema          =  Mongoose.Schema; //  The  data  schema  for  an  event  that  we're  tracking  in  our  analytics  engine var  analyticEventSchema  =  new  Schema({    category            :  {  type:  String,  required:  true,  trim:  true  },    action                :  {  type:  String,  required:  true,  trim:  true  },    label                  :  {  type:  String,  trim:  true  },    source                :  {  type:  String,  required:  true,trim:  true    },              dateCreated      :  {  type:  Date,      required:  true,  default:  Date.now  } }); var  analyticEvent  =  Mongoose.model('analytic_event',  analyticEventSchema); module.exports  =  {    AnalyticEvent:  analyticEvent }; /models/analyticEvent.js
  37. the analytic event model var  Mongoose      =  require('mongoose');

    var  Schema          =  Mongoose.Schema; //  The  data  schema  for  an  event  that  we're  tracking  in  our  analytics  engine var  analyticEventSchema  =  new  Schema({    category            :  {  type:  String,  required:  true,  trim:  true  },    action                :  {  type:  String,  required:  true,  trim:  true  },    label                  :  {  type:  String,  trim:  true  },    source                :  {  type:  String,  required:  true,trim:  true    },    dateCreated      :  {  type:  Date,      required:  true,  default:  Date.now  } }); var  analyticEvent  =  Mongoose.model('analytic_event',  analyticEventSchema); module.exports  =  {    AnalyticEvent:  analyticEvent }; /models/analyticEvent.js
  38. the analytic event model var  Mongoose      =  require('mongoose');

    var  Schema          =  Mongoose.Schema; //  The  data  schema  for  an  event  that  we're  tracking  in  our  analytics  engine var  analyticEventSchema  =  new  Schema({    category            :  {  type:  String,  required:  true,  trim:  true  },    action                :  {  type:  String,  required:  true,  trim:  true  },    label                  :  {  type:  String,  trim:  true  },    source                :  {  type:  String,  required:  true,trim:  true    },                  dateCreated      :  {  type:  Date,      required:  true,  default:  Date.now  } }); var  analyticEvent  =  Mongoose.model('analytic_event',  analyticEventSchema); module.exports  =  {    AnalyticEvent:  analyticEvent }; /models/analyticEvent.js
  39. the analytic event model var  Mongoose      =  require('mongoose');

    var  Schema          =  Mongoose.Schema; //  The  data  schema  for  an  event  that  we're  tracking  in  our  analytics  engine var  analyticEventSchema  =  new  Schema({    category            :  {  type:  String,  required:  true,  trim:  true  },    action                :  {  type:  String,  required:  true,  trim:  true  },    label                  :  {  type:  String,  trim:  true  },    source                :  {  type:  String,  required:  true,trim:  true    },\    dateCreated      :  {  type:  Date,      required:  true,  default:  Date.now  } }); var  analyticEvent  =  Mongoose.model('analytic_event',  analyticEventSchema); module.exports  =  {    AnalyticEvent:  analyticEvent }; /models/analyticEvent.js
  40. building the web api

  41. new hapi project mkdir felkerlytics; cd felkerlytics { "name": "analytics-engine",

    "version": "0.0.1", "description": "An example hapi and mongo db app", "main": "server.js", "dependencies": { "hapi": "3.0.1", "mongoose": "~3.8.7", "boom": "^2.2.2", "lodash": "^2.4.1", "joi": "^2.8.0" } } create a package.json file with these contents create a folder for the app $ npm install install dependencies and install express
  42. $ npm ls !"# boom@2.2.2 $ %"" hoek@1.5.2 !"# hapi@3.0.0

    $ !"" async@0.2.10 $ !"" boom@2.2.2 $ !"" catbox@2.1.0 $ !"" catbox-memory@1.0.1 $ !"" cryptiles@2.0.0 $ !"" hoek@1.5.1 $ !"" iron@2.0.1 $ !"" joi@2.8.0 $ !"" lru-cache@2.5.0 $ !"" mime@1.2.11 $ !"# multiparty@3.2.3 $ $ !"# readable-stream@1.1.11 $ $ $ !"" core-util-is@1.0.1 $ $ $ !"" debuglog@0.0.2 $ $ $ %"" string_decoder@0.10.25-1 $ $ %"" stream-counter@0.2.0 $ !"" negotiator@0.4.2 $ !"" nipple@2.4.0 $ !"# optimist@0.6.1 $ $ !"" minimist@0.0.8 $ $ %"" wordwrap@0.0.2 $ !"" qs@0.6.6 $ !"" semver@2.2.1 $ %"" shot@1.3.2 !"# joi@2.8.0 $ %"" hoek@1.5.2 %"# mongoose@3.8.8 !"" hooks@0.2.1 !"# mongodb@1.3.23 $ !"" bson@0.2.5 $ %"" kerberos@0.0.3 !"" mpath@0.1.1 !"" mpromise@0.4.3 !"# mquery@0.5.3 $ %"" debug@0.7.4 !"" ms@0.1.0 !"" muri@0.3.1 !"" regexp-clone@0.0.1 %"" sliced@0.0.5
  43. authentication basic passport.js hawk / oz

  44. ok stop - code time

  45. learn js the right way

  46. github.com/donnfelker/ @donnfelker code twitter MongoHub