class: center, middle, inverse # Cours NoSQL: Node.js ## Haïkel Guémar - haikel.guemar@gmail.com --- class: center, middle # Introduction ![logo](img/nodejs-logo.png) --- class: middle ## Installation http://nodejs.org/download --- class: middle ## Tester son installation ```bash $ node > console.log('hello world!') ``` --- class: middle ## Synchrone ```javascript var doc = db.things.findOne() printjson(doc) ```
--- class: middle ## Asynchrone ```javascript var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://127.0.0.1/test', function(err, db) { if (err) throw err; // gestion d'erreur db.collection('things').findOne({}, function(err, doc) { console.dir(doc); db.close(doc); }); console.dir('Found a document'); }); ``` --- class: middle ## Asynchrone
--- class: middle ## Hello World avec Node.js ```javascript var http = require('http'); var server = http.createServer(function(request, response) { response.writeHead(200, {"ContentType": "text/plain"}); response.end("Hello World!"); }); server.listen(8000) // Cf. http://localhost:8000 ``` --- class: middle ## Node Packages Manager (NPM) ```bash $ npm install express consolidate pug mongodb ``` --- class: middle ## Packages.json ```javascript { "name": "first_app", "version": "0.0.1", "description": "first node app", "main": "app.js", "dependencies": { "consolidate": "~0.11.0", "express": "~4.12.1", "mongodb": "~1.4.32" }, "author": "Bob Leponge", "license": "BSD" } ``` ```bash $ npm install ``` --- class: middle ## Hello world avec Express ```javascript var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send("Hello World!"); }); app.listen(8000); console.log("Express server started on 8000"); ``` --- class: middle ## Express et les middlewares
--- class: middle, center, inverse # Vues et Templates --- class: middle ## Pug * Pug est un moteur de template * Consolidate est une bibliothèque facilitant l'intégration des moteurs de templates --- class: middle ## Pug (1/2) Dans un fichier views/hello.html ```javascript doctype html html(lang="en") head title Hello World! body h1 Hello #{name} ``` --- class: middle ## Pug (2/2) ```javascript var express = require('express'); var cons = require('consolidate'); var app = express(); app.engine('html', cons.pug); app.set('view engine', 'html'); app.set('views', __dirname + '/views') app.get('/', function(req, res) { res.render("hello", {"name": "pug"}); }); app.get('*', function(req, res) { res.send("Page not found", 404); }); app.listen(8000); console.log("Express server started on 8000"); ``` --- class: center, middle, inverse # Appliquons ! --- class: middle ## Driver mongodb recommandé * Le driver officiel https://www.npmjs.com/package/mongodb --- class: middle ## Remplissons la base ```bash $ mongo > use cours > db.mongoexpress.insert({"name": "MongoDB"}) ``` --- class: middle ## Les bases ```javascript var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017'; var dbName = 'mongoexpress'; MongoClient.connect(url, function(err, client) { console.log("Connection succeeded"); var db = client.db(dbName); /* On fait des choses */ client.close(); } ``` --- class: middle ## Application (1/2) ```javascript var express = require('express'); var cons = require('consolidate'); var app = express(); var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017'; var dbName = 'cours2019'; app.engine('html', cons.pug); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); app.get('/', function(req, res) { app.db.collection('mongoexpress').findOne({}, function(err, doc) { res.render("hello", doc); }); }); app.get('*', function(req, res) { res.send("Page not found", 404); }); ``` --- class: middle ## Application (2/2) ```javascript MongoClient.connect(url, function(err, client) { app.client = client; app.db = client.db(dbName); app.listen(8000); console.log("Express server started on 8000"); }); ``` --- class: middle, center, inverse # Récupérer des paramètres avec GET --- class: middle ## Gérer les requêtes GET avec Express Supposons que l'on a une url http://localhost:8000/bob?job=firefighter&age=27 * paramètre url: bob * paramètres query: job => firefighter, age => 27 --- class: middle ## Le template hello.html ```javascript doctype html html(lang="en") head title Hello World! body h1 Hello #{name} here are your GET variables ul li #{job} li #{age} years ``` --- class: middle ## le code ```javascript var express = require('express'); var cons = require('consolidate'); var app = express(); app.engine('html', cons.pug); app.set('view engine', 'html'); app.set('views', __dirname + '/views') app.get('/:name', function(req, res, next) { var name = req.params.name var job = req.query.job; var age = req.query.age; res.render("hello", {'name': name, 'job': job, 'age': age}); }); app.get('*', function(req, res) { res.send("Page not found", 404); }); app.listen(8000); console.log("Express server started on 8000"); ``` --- class: middle, center, inverse # Récupérer des paramètres avec GET --- class: middle ## Body-parser ```bash $ npm install --save body-parser ``` --- class: middle ## Le template fruit_picker.html ```javascript doctype html html(lang="en") head title Fruit Picker body form(action='/fruit_picker', method='POST') p Quel est votre fruit préféré ? each val in fruits - var inputValue = val p input(type="radio", name="fruit", value=inputValue) | #{val} input(type="submit", value="submit") ``` --- class: middle ## Gérer les requêtes POST avec Express ```javascript var express = require('express'); var cons = require('consolidate'); var bodyParser = require('body-parser'); var app = express(); app.engine('html', cons.pug); app.set('view engine', 'html'); app.set('views', __dirname + '/views') app.use(bodyParser()) app.get('/', function(req, res, next) { res.render("fruit_picker", {'fruits': ['pomme', 'poire', 'pêche', 'banane']}); }); app.post('/fruit_picker', function(req, res, next) { var favorite = req.body.fruit; if (typeof favorite == 'undefined') { next(Error('Please choose a fruit')); } else { res.send("Ton fruit préféré est " + favorite); } }); app.listen(8000); console.log("Express server started on 8000"); ``` --- class: center, inverse, middle # TD --- class: middle ## Code moi un blog 1. comment modéliseriez-vous la base de données avec un SGBDR 2. comment le feriez-vous avec MongoDB ? --- class: middle ## Avec MongoDB ```javascript posts: { 'title': 'cours nosql', 'body': '...', 'author': '...', 'date': '...', 'comments': [{'name': 'Joe', 'email': 'joe@doe.com', 'comment': '...'}, ... ], 'tags': ['cours', 'nosql', ...] } authors: {_id: '...', 'password': '...'} ``` --- class: middle, center, inverse # Q/A