Introduction to buildREST API with
WhatisNode.js ? 
«Aplatform built onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ 
Node.js isneithera server nora web framework
About Node.js 
•Createdby Ryan Dahl in 2009 
•Development and maintenance sponsored byJoyent 
•LicenceMIT 
•Last release : 0.10.31 
•Based on Google V8 Engine 
•+99 000 packages
Successstories 
Rails to Node 
« Servers were cut to 3 from 30 » 
« Running up to 20x faster in some scenarios » 
« Frontend and backend mobile teams could be combined […] » 
Java to Node 
« Built almost twice as fast with fewer people » 
« Double the requests per second » 
« 35% decrease in the average response time »
Architecture 
•Single Threaded 
•Event Loop 
•Non-blockingI/O 
•Javascript(Event DrivenLanguage)
Inside Node.js 
Standard JavaScript with 
•Buffer 
•C/C++ Addons 
•Child Processes 
•Cluster 
•Console 
•Crypto 
•Debugger 
•DNS 
•Domain 
•Events 
•File System 
•Globals 
•HTTP 
•HTTPS 
•Modules 
•Net 
•OS 
•Path 
•Process 
•Punycode 
•QueryStrings 
•Readline 
•REPL 
•Stream 
•String Decoder 
•Timers 
•TLS/SSL 
•TTY 
•UDP/Datagram 
•URL 
•Utilities 
•VM 
•ZLIB 
… but withoutDOM manipulation
File package.json 
Project informations 
•Name 
•Version 
•Dependencies 
•Licence 
•Main file 
•Etc...
NPM (NodePackagedModules) 
•Findpackages : https://www.npmjs.org/ 
•Help : npm-l 
•Createpackage.json: npminit 
•Install package : 
•npminstallexpress 
•npminstallmongosse--save 
•npminstall-g mocha 
•npm installgrunt--save-dev 
•Update project from package.json 
•npm install 
•npm update
Hello Node.js 
console.log("Hello World !"); 
hello.js 
> nodehello.js 
Hello World !
Loadmodule 
•Coremodule : var http = require('http'); 
•Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); 
•Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
Createmodule 1/2 
var PI = Math.PI; 
exports.area= function(r) { 
return PI * r * r; 
}; 
var circle= require('./circle.js'); 
console.log('The area of a circle of radius 4 is '+ circle.area(4)); 
circle.js
Createmodule 2/2 
var PI = Math.PI; 
module.exports= function(r) { 
return PI * r * r; 
}; 
var circleArea= require('./circle-area.js'); 
console.log('The area of a circle of radius 4 is '+ circleArea(4)); 
circle-area.js
Node.js 
Talk is cheapShow me the code
Express introduction 
«Fast, unopinionated, minimalist web framework forNode.js» http://expressjs.com
Express sample 
var express = require('express'); 
var app= express(); 
app.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
app.post('/:name', function (req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
app.listen(3000);
Express middleware 
Middleware can: 
•Execute any code. 
•Make changes to the request and the response objects. 
•End the request-response cycle. 
•Call the next middleware in the stack. 
var express = require('express'); 
var app= express(); 
var cookieParser= require('cookie-parser'); 
app.use(express.static(__dirname+ '/public')); 
app.use(cookieParser()); 
…
Express middleware modules 
Module 
Description 
morgan 
HTTP request logger middleware for node.js 
express.static 
Serve static content from the "public" directory (js, css, html, image, video, …) 
body-parser 
Parserequestbody and populatereq.body(ie: parsejsonbody) 
cookie-parser 
Parse cookie header and populate req.cookieswith an object keyed by the cookie names 
cookie-session 
Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. 
express-session 
Providegenericsession functionality within-memorystorage by default 
method-override 
Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. 
csurf 
Node.js CSRF protection middleware. 
…
Express router 
var express = require('express'); 
var router = express.Router(); 
router.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
router.post('/:name', function(req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
var app= express(); 
app.use('/api/', router);
Express 
Talk is cheapShow me the code
Mongooseintroduction 
«Elegantmongodbobjectmodelingfornode.js » http://mongoosejs.com/
Mongooseconnect 
var mongoose= require('mongoose'); 
mongoose.connect('mongodb://localhost/test'); 
mongoose.connection.on('error', console.log); 
mongoose.connection.once('open', functioncallback (){ }); 
mongoose.connection.on('disconnected', functioncallback (){ });
Mongooseschema1/2 
/* Article Schema*/ 
var ArticleSchema= new Schema({ 
title: {type : String, trim : true}, 
body: {type : String, trim: true}, 
user: {type : Schema.ObjectId, ref: 'User'}, 
comments: [{ 
body: { type : String, default : '' }, 
user: { type : Schema.ObjectId, ref: 'User' }, 
createdAt: { type : Date, default : Date.now} 
}], 
createdAt: {type : Date, default : Date.now} 
}); 
/* Validations */ 
ArticleSchema.path('title').required(true, 'Article title cannot be blank'); 
ArticleSchema.path('body').required(true, 'Article body cannot be blank'); 
/* Save the Schema*/ 
mongoose.model('Article', ArticleSchema);
Mongooseschema2/2 
Othersschemafeatures: 
•Validator 
•Virtual property 
•Middleware 
•Population 
•…
Mongooseinstance & save 
/* Getthe model */ 
var Article = mongoose.model('Article'); 
/* Createa new instance */ 
var article = new Article({ 
title: 'Introduction to Mongoose', 
body : 'This is an article about Mongoose' 
}); 
/* Save the instance */ 
article.save(function(err){ 
if(err) return console.log("not saved !"); 
console.log("saved"); 
});
Mongoosequery 
var Article = mongoose.model('Article'); 
// A query 
Article 
.where('user').equals(myUserId) 
.where('tile', /mongoose/i) 
.select('titlebody createdAt') 
.sort('-createdAt') 
.limit(10) 
.exec (function (err, data){ /* do anything */ }); 
// The samequery 
Article.find({ 
user : myUserId, 
title: /mongoose/i 
}, 
'titlebody createdAt', 
{ 
sort : '-createdAt', 
limit: 10 
}, 
function (err, data){ /* do anything */ } 
);
Mongoose 
Talk is cheapShow me the code
Othersmodules 
•Web frameworksExpress, Koa, Sails, Hapi, Restify, … 
•Server toolsSocket.io, Passport, … 
•LoggersWinston, Bunyan, … 
•ToolsAsync, Q, Lodash, Moment, Cheerio, … 
•TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …
Questions?

Introduction to REST API with Node.js

  • 1.
  • 2.
    WhatisNode.js ? «Aplatformbuilt onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ Node.js isneithera server nora web framework
  • 3.
    About Node.js •CreatedbyRyan Dahl in 2009 •Development and maintenance sponsored byJoyent •LicenceMIT •Last release : 0.10.31 •Based on Google V8 Engine •+99 000 packages
  • 4.
    Successstories Rails toNode « Servers were cut to 3 from 30 » « Running up to 20x faster in some scenarios » « Frontend and backend mobile teams could be combined […] » Java to Node « Built almost twice as fast with fewer people » « Double the requests per second » « 35% decrease in the average response time »
  • 5.
    Architecture •Single Threaded •Event Loop •Non-blockingI/O •Javascript(Event DrivenLanguage)
  • 7.
    Inside Node.js StandardJavaScript with •Buffer •C/C++ Addons •Child Processes •Cluster •Console •Crypto •Debugger •DNS •Domain •Events •File System •Globals •HTTP •HTTPS •Modules •Net •OS •Path •Process •Punycode •QueryStrings •Readline •REPL •Stream •String Decoder •Timers •TLS/SSL •TTY •UDP/Datagram •URL •Utilities •VM •ZLIB … but withoutDOM manipulation
  • 8.
    File package.json Projectinformations •Name •Version •Dependencies •Licence •Main file •Etc...
  • 9.
    NPM (NodePackagedModules) •Findpackages: https://www.npmjs.org/ •Help : npm-l •Createpackage.json: npminit •Install package : •npminstallexpress •npminstallmongosse--save •npminstall-g mocha •npm installgrunt--save-dev •Update project from package.json •npm install •npm update
  • 10.
    Hello Node.js console.log("HelloWorld !"); hello.js > nodehello.js Hello World !
  • 11.
    Loadmodule •Coremodule :var http = require('http'); •Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); •Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
  • 12.
    Createmodule 1/2 varPI = Math.PI; exports.area= function(r) { return PI * r * r; }; var circle= require('./circle.js'); console.log('The area of a circle of radius 4 is '+ circle.area(4)); circle.js
  • 13.
    Createmodule 2/2 varPI = Math.PI; module.exports= function(r) { return PI * r * r; }; var circleArea= require('./circle-area.js'); console.log('The area of a circle of radius 4 is '+ circleArea(4)); circle-area.js
  • 14.
    Node.js Talk ischeapShow me the code
  • 15.
    Express introduction «Fast,unopinionated, minimalist web framework forNode.js» http://expressjs.com
  • 16.
    Express sample varexpress = require('express'); var app= express(); app.get('/', function(req, res) { res.send('Hello World!'); }); app.post('/:name', function (req, res) { res.send('Hello !'+req.param('name')); }); app.listen(3000);
  • 17.
    Express middleware Middlewarecan: •Execute any code. •Make changes to the request and the response objects. •End the request-response cycle. •Call the next middleware in the stack. var express = require('express'); var app= express(); var cookieParser= require('cookie-parser'); app.use(express.static(__dirname+ '/public')); app.use(cookieParser()); …
  • 18.
    Express middleware modules Module Description morgan HTTP request logger middleware for node.js express.static Serve static content from the "public" directory (js, css, html, image, video, …) body-parser Parserequestbody and populatereq.body(ie: parsejsonbody) cookie-parser Parse cookie header and populate req.cookieswith an object keyed by the cookie names cookie-session Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. express-session Providegenericsession functionality within-memorystorage by default method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. csurf Node.js CSRF protection middleware. …
  • 19.
    Express router varexpress = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('Hello World!'); }); router.post('/:name', function(req, res) { res.send('Hello !'+req.param('name')); }); var app= express(); app.use('/api/', router);
  • 20.
    Express Talk ischeapShow me the code
  • 21.
  • 22.
    Mongooseconnect var mongoose=require('mongoose'); mongoose.connect('mongodb://localhost/test'); mongoose.connection.on('error', console.log); mongoose.connection.once('open', functioncallback (){ }); mongoose.connection.on('disconnected', functioncallback (){ });
  • 23.
    Mongooseschema1/2 /* ArticleSchema*/ var ArticleSchema= new Schema({ title: {type : String, trim : true}, body: {type : String, trim: true}, user: {type : Schema.ObjectId, ref: 'User'}, comments: [{ body: { type : String, default : '' }, user: { type : Schema.ObjectId, ref: 'User' }, createdAt: { type : Date, default : Date.now} }], createdAt: {type : Date, default : Date.now} }); /* Validations */ ArticleSchema.path('title').required(true, 'Article title cannot be blank'); ArticleSchema.path('body').required(true, 'Article body cannot be blank'); /* Save the Schema*/ mongoose.model('Article', ArticleSchema);
  • 24.
    Mongooseschema2/2 Othersschemafeatures: •Validator •Virtual property •Middleware •Population •…
  • 25.
    Mongooseinstance & save /* Getthe model */ var Article = mongoose.model('Article'); /* Createa new instance */ var article = new Article({ title: 'Introduction to Mongoose', body : 'This is an article about Mongoose' }); /* Save the instance */ article.save(function(err){ if(err) return console.log("not saved !"); console.log("saved"); });
  • 26.
    Mongoosequery var Article= mongoose.model('Article'); // A query Article .where('user').equals(myUserId) .where('tile', /mongoose/i) .select('titlebody createdAt') .sort('-createdAt') .limit(10) .exec (function (err, data){ /* do anything */ }); // The samequery Article.find({ user : myUserId, title: /mongoose/i }, 'titlebody createdAt', { sort : '-createdAt', limit: 10 }, function (err, data){ /* do anything */ } );
  • 27.
    Mongoose Talk ischeapShow me the code
  • 28.
    Othersmodules •Web frameworksExpress,Koa, Sails, Hapi, Restify, … •Server toolsSocket.io, Passport, … •LoggersWinston, Bunyan, … •ToolsAsync, Q, Lodash, Moment, Cheerio, … •TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …
  • 29.