SlideShare a Scribd company logo
Node.js e
MongoDB
http://www.luiztools.com.br
MongoDB - Movies
Server - Movies
Api - Movies
Index - Movies
CRONOGRAMA
MongoDB -
Movies
MongoDB - Movies
nano /cinema-microservice/movies-
service/src/repository/repository.js
nano /cinema-microservice/movies-
service/src/repository/repository.test.js
Repositório
MongoDB - Movies
const mongodb = require("../config/mongodb");
function getAllMovies(callback){
mongodb.connect((err, db) => {
db.collection("movies").find().toArray(callback);
})
}
repository.js
MongoDB - Movies
function getMovieById(id, callback){
mongodb.connect((err, db) => {
db.collection("movies").findOne({_id:
require("mongodb").ObjectId(id)}, callback);
});
}
repository.js
MongoDB - Movies
function getMoviePremiers(callback){
var monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);
monthAgo.setHours(0, 0, 0);
monthAgo.setMilliseconds(0);
mongodb.connect((err, db) => {
db.collection("movies").find({ dataLancamento: {
$gte: monthAgo } }).toArray(callback);
});
}
repository.js
MongoDB - Movies
function disconnect(){
return mongodb.disconnect();
}
module.exports = { getAllMovies, getMovieById,
getMoviePremiers, disconnect }
repository.js
MongoDB - Movies
const test = require('tape');
const repository = require('./repository');
function runTests(){
var id = null;
//tests here
}
module.exports = { runTests }
repository.test.js
MongoDB - Movies
var id = null;
test('Repository GetAllMovies', (t) => {
repository.getAllMovies((err, movies) => {
if(movies && movies.length > 0) id =
movies[0]._id;
t.assert(!err && movies && movies.length > 0,
"All Movies Returned");
t.end();
});
})
repository.test.js
MongoDB - Movies
test('Repository GetMovieById', (t) => {
if(!id) {
t.assert(false, "Movie by Id Returned");
t.end();
return;
}
repository.getMovieById(id, (err, movie) => {
t.assert(!err && movie, "Movie by Id
Returned");
t.end();
});
})
repository.test.js
MongoDB - Movies
test('Repository GetMoviePremiers', (t) => {
repository.getMoviePremiers((err, movies) => {
t.assert(!err && movies && movies.length > 0,
"Movie Premiers Returned");
t.end();
});
})
repository.test.js
MongoDB - Movies
test('Repository Disconnect', (t) => {
t.assert(repository.disconnect(), "Disconnect
Ok");
t.end();
})
repository.test.js
MongoDB - Movies
require("dotenv-safe").load();
require("./config/mongodb.test").runTests();
require("./repository/repository.test").runTests();
index.test.js
MongoDB - Movies
Server -
Movies
Server - Movies
nano /cinema-microservice/movies-
service/src/server/server.js
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
var server = null;
server.js
Server - Movies
function start(api, repository, callback){
const app = express();
app.use(morgan('dev'));
app.use(helmet());
app.use((err, req, res, next) => {
callback(new Error('Something went wrong!, err:' +
err), null);
res.status(500).send('Something went wrong!');
})
api(app, repository);
server = app.listen(parseInt(process.env.PORT), () =>
callback(null, server));
}
server.js
Server - Movies
function stop(){
if(server) server.close();
return true;
}
module.exports = { start, stop }
server.js
Server - Movies
nano /cinema-microservice/movies-
service/src/server/server.test.js
server.test.js
Server - Movies
const test = require('tape');
const server = require('./server');
function apiMock(app, repo){
console.log("do nothing");
}
function runTests(){
//tests here
}
module.exports = { runTests }
server.test.js
Server - Movies
test('Server Start', (t) => {
server.start(apiMock, null, (err, srv) => {
t.assert(!err && srv, "Server started");
t.end();
});
})
test('Server Stop', (t) => {
t.assert(server.stop(), "Server stopped");
t.end();
})
server.test.js
Tape
API -
Movies
API - Movies
nano /cinema-microservice/movies-
service/src/api/movies.js
movies.js
API - Movies
module.exports = (app, repository) => {
app.get('/movies', (req, res, next) => {
repository.getAllMovies((err, movies) => {
if(err) return next(err);
res.json(movies);
});
})
movies.js
API - Movies
app.get('/movies/premieres', (req, res, next) => {
repository.getMoviePremiers((err, movies) => {
if(err) return next(err);
res.json(movies)
});
})
movies.js
API - Movies
app.get('/movies/:id', (req, res, next) => {
repository.getMovieById(req.params.id, (err, movie)
=> {
if(err) return next(err);
res.json(movie)
});
})
}
movies.js
Server - Movies
npm install supertest
nano /cinema-microservice/movies-
service/src/api/movies.test.js
movies.test.js
Server - Movies
npm install supertest
nano /cinema-microservice/movies-
service/src/api/movies.test.js
const test = require('tape');
const supertest = require('supertest');
const movies = require('./movies');
const server = require("../server/server");
const repository = require("../repository/repository");
movies.test.js
Server - Movies
function runTests(){
var app = null;
server.start(movies, repository, (err, app) => {
//tests here
server.stop();
})
}
module.exports = { runTests }
movies.test.js
Server - Movies
var id = null;
test('GET /movies', (t) => {
supertest(app)
.get('/movies')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) =>{
if(res.body && res.body.length > 0)
id = res.body[0]._id;
t.assert(res.body && res.body.length > 0,
"All Movies returned")
t.end()
})
})
movies.test.js
Server - Movies
test('GET /movies/:id', (t) => {
if(!id) {
t.assert(false, "Movie by Id Returned");
t.end();
return;
}
supertest(app)
.get('/movies/' + id)
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) =>{
t.assert(res.body, "Movies By Idreturned")
t.end()
})
})
movies.test.js
Server - Movies
test('GET /movies/premieres', (t) => {
supertest(app)
.get('/movies/premieres')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) =>{
t.assert(res.body && res.body.length
> 0, "Premiere Movies returned")
t.end()
})
})
movies.test.js
Server - Movies
Index -
Movies
Index - Movies
nano /cinema-microservice/movies-service/src/index.js
require("dotenv-safe").load();
const movies = require('./api/movies');
const server = require("./server/server");
const repository = require("./repository/repository");
server.start(movies, repository, (err, app) => {
console.log("just started");
});
index.js
Index - Movies
Dúvidas?
Exercícios
1 Adicione busca por nome no microservice
2 Adicione paginação no getAllMovies
3 Adicione o restante do CRUD ao microservice
Obrigado!

More Related Content

What's hot

Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
emptysquare
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
RDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по Dip
RAMBLER&Co
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
Ihsan Fauzi Rahman
 
RingoJS
RingoJSRingoJS
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
Tsuyoshi Yamamoto
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
Filipe Ximenes
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Filipe Ximenes
 
Python Yield
Python YieldPython Yield
Python Yield
yangjuven
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
GlobalLogic Ukraine
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
Wilson Su
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
PeckaDesign.cz
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
Eyal Vardi
 
What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?
emptysquare
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
RameshNair6
 

What's hot (20)

Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
RDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по Dip
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
 
RingoJS
RingoJSRingoJS
RingoJS
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
 
Python Yield
Python YieldPython Yield
Python Yield
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
 
What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous Beasts
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 

Similar to Curso de Node.js e MongoDB - 16

Modules and injector
Modules and injectorModules and injector
Modules and injector
Eyal Vardi
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Wim Selles
 
How to React Native
How to React NativeHow to React Native
How to React Native
Dmitry Ulyanov
 
20150319 testotipsio
20150319 testotipsio20150319 testotipsio
20150319 testotipsio
Kazuaki Matsuo
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
Marcin Wosinek
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
Dmitriy Sobko
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
Javier Abadía
 
Android workshop
Android workshopAndroid workshop
Android workshop
Michael Galpin
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
Laurent_VB
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
Daniel Cukier
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
EPAM Systems
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
Babacar NIANG
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
Tatsuhiko Miyagawa
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
Ben Lin
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
Amazon Web Services
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 

Similar to Curso de Node.js e MongoDB - 16 (20)

Modules and injector
Modules and injectorModules and injector
Modules and injector
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
 
How to React Native
How to React NativeHow to React Native
How to React Native
 
20150319 testotipsio
20150319 testotipsio20150319 testotipsio
20150319 testotipsio
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular js
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 

More from Luiz Duarte

Mecanismo de busca em Node.js e MongoDB
Mecanismo de busca em Node.js e MongoDBMecanismo de busca em Node.js e MongoDB
Mecanismo de busca em Node.js e MongoDB
Luiz Duarte
 
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
Luiz Duarte
 
Team Building: Passo a Passo
Team Building: Passo a PassoTeam Building: Passo a Passo
Team Building: Passo a Passo
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 07
Curso Scrum e Métodos Ágeis 07Curso Scrum e Métodos Ágeis 07
Curso Scrum e Métodos Ágeis 07
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 04
Curso Scrum e Métodos Ágeis 04Curso Scrum e Métodos Ágeis 04
Curso Scrum e Métodos Ágeis 04
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 02
Curso Scrum e Métodos Ágeis 02Curso Scrum e Métodos Ágeis 02
Curso Scrum e Métodos Ágeis 02
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 03
Curso Scrum e Métodos Ágeis 03Curso Scrum e Métodos Ágeis 03
Curso Scrum e Métodos Ágeis 03
Luiz Duarte
 
Curso Scrum e Métodos Ágeis - Introdução
Curso Scrum e Métodos Ágeis - IntroduçãoCurso Scrum e Métodos Ágeis - Introdução
Curso Scrum e Métodos Ágeis - Introdução
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 01
Curso Scrum e Métodos Ágeis 01Curso Scrum e Métodos Ágeis 01
Curso Scrum e Métodos Ágeis 01
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 05
Curso Scrum e Métodos Ágeis 05Curso Scrum e Métodos Ágeis 05
Curso Scrum e Métodos Ágeis 05
Luiz Duarte
 
Curso Scrum e Métodos Ágeis 06
Curso Scrum e Métodos Ágeis 06Curso Scrum e Métodos Ágeis 06
Curso Scrum e Métodos Ágeis 06
Luiz Duarte
 
Carreira em Agilidade
Carreira em AgilidadeCarreira em Agilidade
Carreira em Agilidade
Luiz Duarte
 
Gamification em Modelos de Maturidade
Gamification em Modelos de MaturidadeGamification em Modelos de Maturidade
Gamification em Modelos de Maturidade
Luiz Duarte
 
Curso de Node.js e MongoDB - 20
Curso de Node.js e MongoDB - 20Curso de Node.js e MongoDB - 20
Curso de Node.js e MongoDB - 20
Luiz Duarte
 
Curso de Node.js e MongoDB - 19
Curso de Node.js e MongoDB - 19Curso de Node.js e MongoDB - 19
Curso de Node.js e MongoDB - 19
Luiz Duarte
 
Curso de Node.js e MongoDB - 18
Curso de Node.js e MongoDB - 18Curso de Node.js e MongoDB - 18
Curso de Node.js e MongoDB - 18
Luiz Duarte
 
Curso de Node.js e MongoDB - 17
Curso de Node.js e MongoDB - 17Curso de Node.js e MongoDB - 17
Curso de Node.js e MongoDB - 17
Luiz Duarte
 
Curso de Node.js e MongoDB - 15
Curso de Node.js e MongoDB - 15Curso de Node.js e MongoDB - 15
Curso de Node.js e MongoDB - 15
Luiz Duarte
 
Curso de Node.js e MongoDB - 14
Curso de Node.js e MongoDB - 14Curso de Node.js e MongoDB - 14
Curso de Node.js e MongoDB - 14
Luiz Duarte
 
Curso de Node.js e MongoDB - 13
Curso de Node.js e MongoDB - 13Curso de Node.js e MongoDB - 13
Curso de Node.js e MongoDB - 13
Luiz Duarte
 

More from Luiz Duarte (20)

Mecanismo de busca em Node.js e MongoDB
Mecanismo de busca em Node.js e MongoDBMecanismo de busca em Node.js e MongoDB
Mecanismo de busca em Node.js e MongoDB
 
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
FDP, DEEP, INVEST e SMART: entendendo a sopa de letrinhas que todo PO deve co...
 
Team Building: Passo a Passo
Team Building: Passo a PassoTeam Building: Passo a Passo
Team Building: Passo a Passo
 
Curso Scrum e Métodos Ágeis 07
Curso Scrum e Métodos Ágeis 07Curso Scrum e Métodos Ágeis 07
Curso Scrum e Métodos Ágeis 07
 
Curso Scrum e Métodos Ágeis 04
Curso Scrum e Métodos Ágeis 04Curso Scrum e Métodos Ágeis 04
Curso Scrum e Métodos Ágeis 04
 
Curso Scrum e Métodos Ágeis 02
Curso Scrum e Métodos Ágeis 02Curso Scrum e Métodos Ágeis 02
Curso Scrum e Métodos Ágeis 02
 
Curso Scrum e Métodos Ágeis 03
Curso Scrum e Métodos Ágeis 03Curso Scrum e Métodos Ágeis 03
Curso Scrum e Métodos Ágeis 03
 
Curso Scrum e Métodos Ágeis - Introdução
Curso Scrum e Métodos Ágeis - IntroduçãoCurso Scrum e Métodos Ágeis - Introdução
Curso Scrum e Métodos Ágeis - Introdução
 
Curso Scrum e Métodos Ágeis 01
Curso Scrum e Métodos Ágeis 01Curso Scrum e Métodos Ágeis 01
Curso Scrum e Métodos Ágeis 01
 
Curso Scrum e Métodos Ágeis 05
Curso Scrum e Métodos Ágeis 05Curso Scrum e Métodos Ágeis 05
Curso Scrum e Métodos Ágeis 05
 
Curso Scrum e Métodos Ágeis 06
Curso Scrum e Métodos Ágeis 06Curso Scrum e Métodos Ágeis 06
Curso Scrum e Métodos Ágeis 06
 
Carreira em Agilidade
Carreira em AgilidadeCarreira em Agilidade
Carreira em Agilidade
 
Gamification em Modelos de Maturidade
Gamification em Modelos de MaturidadeGamification em Modelos de Maturidade
Gamification em Modelos de Maturidade
 
Curso de Node.js e MongoDB - 20
Curso de Node.js e MongoDB - 20Curso de Node.js e MongoDB - 20
Curso de Node.js e MongoDB - 20
 
Curso de Node.js e MongoDB - 19
Curso de Node.js e MongoDB - 19Curso de Node.js e MongoDB - 19
Curso de Node.js e MongoDB - 19
 
Curso de Node.js e MongoDB - 18
Curso de Node.js e MongoDB - 18Curso de Node.js e MongoDB - 18
Curso de Node.js e MongoDB - 18
 
Curso de Node.js e MongoDB - 17
Curso de Node.js e MongoDB - 17Curso de Node.js e MongoDB - 17
Curso de Node.js e MongoDB - 17
 
Curso de Node.js e MongoDB - 15
Curso de Node.js e MongoDB - 15Curso de Node.js e MongoDB - 15
Curso de Node.js e MongoDB - 15
 
Curso de Node.js e MongoDB - 14
Curso de Node.js e MongoDB - 14Curso de Node.js e MongoDB - 14
Curso de Node.js e MongoDB - 14
 
Curso de Node.js e MongoDB - 13
Curso de Node.js e MongoDB - 13Curso de Node.js e MongoDB - 13
Curso de Node.js e MongoDB - 13
 

Recently uploaded

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
Zycus
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 

Recently uploaded (20)

Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 

Curso de Node.js e MongoDB - 16

  • 2. MongoDB - Movies Server - Movies Api - Movies Index - Movies CRONOGRAMA
  • 4. MongoDB - Movies nano /cinema-microservice/movies- service/src/repository/repository.js nano /cinema-microservice/movies- service/src/repository/repository.test.js Repositório
  • 5. MongoDB - Movies const mongodb = require("../config/mongodb"); function getAllMovies(callback){ mongodb.connect((err, db) => { db.collection("movies").find().toArray(callback); }) } repository.js
  • 6. MongoDB - Movies function getMovieById(id, callback){ mongodb.connect((err, db) => { db.collection("movies").findOne({_id: require("mongodb").ObjectId(id)}, callback); }); } repository.js
  • 7. MongoDB - Movies function getMoviePremiers(callback){ var monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); monthAgo.setHours(0, 0, 0); monthAgo.setMilliseconds(0); mongodb.connect((err, db) => { db.collection("movies").find({ dataLancamento: { $gte: monthAgo } }).toArray(callback); }); } repository.js
  • 8. MongoDB - Movies function disconnect(){ return mongodb.disconnect(); } module.exports = { getAllMovies, getMovieById, getMoviePremiers, disconnect } repository.js
  • 9. MongoDB - Movies const test = require('tape'); const repository = require('./repository'); function runTests(){ var id = null; //tests here } module.exports = { runTests } repository.test.js
  • 10. MongoDB - Movies var id = null; test('Repository GetAllMovies', (t) => { repository.getAllMovies((err, movies) => { if(movies && movies.length > 0) id = movies[0]._id; t.assert(!err && movies && movies.length > 0, "All Movies Returned"); t.end(); }); }) repository.test.js
  • 11. MongoDB - Movies test('Repository GetMovieById', (t) => { if(!id) { t.assert(false, "Movie by Id Returned"); t.end(); return; } repository.getMovieById(id, (err, movie) => { t.assert(!err && movie, "Movie by Id Returned"); t.end(); }); }) repository.test.js
  • 12. MongoDB - Movies test('Repository GetMoviePremiers', (t) => { repository.getMoviePremiers((err, movies) => { t.assert(!err && movies && movies.length > 0, "Movie Premiers Returned"); t.end(); }); }) repository.test.js
  • 13. MongoDB - Movies test('Repository Disconnect', (t) => { t.assert(repository.disconnect(), "Disconnect Ok"); t.end(); }) repository.test.js
  • 17. Server - Movies nano /cinema-microservice/movies- service/src/server/server.js const express = require('express'); const morgan = require('morgan'); const helmet = require('helmet'); var server = null; server.js
  • 18. Server - Movies function start(api, repository, callback){ const app = express(); app.use(morgan('dev')); app.use(helmet()); app.use((err, req, res, next) => { callback(new Error('Something went wrong!, err:' + err), null); res.status(500).send('Something went wrong!'); }) api(app, repository); server = app.listen(parseInt(process.env.PORT), () => callback(null, server)); } server.js
  • 19. Server - Movies function stop(){ if(server) server.close(); return true; } module.exports = { start, stop } server.js
  • 20. Server - Movies nano /cinema-microservice/movies- service/src/server/server.test.js server.test.js
  • 21. Server - Movies const test = require('tape'); const server = require('./server'); function apiMock(app, repo){ console.log("do nothing"); } function runTests(){ //tests here } module.exports = { runTests } server.test.js
  • 22. Server - Movies test('Server Start', (t) => { server.start(apiMock, null, (err, srv) => { t.assert(!err && srv, "Server started"); t.end(); }); }) test('Server Stop', (t) => { t.assert(server.stop(), "Server stopped"); t.end(); }) server.test.js
  • 23. Tape
  • 25. API - Movies nano /cinema-microservice/movies- service/src/api/movies.js movies.js
  • 26. API - Movies module.exports = (app, repository) => { app.get('/movies', (req, res, next) => { repository.getAllMovies((err, movies) => { if(err) return next(err); res.json(movies); }); }) movies.js
  • 27. API - Movies app.get('/movies/premieres', (req, res, next) => { repository.getMoviePremiers((err, movies) => { if(err) return next(err); res.json(movies) }); }) movies.js
  • 28. API - Movies app.get('/movies/:id', (req, res, next) => { repository.getMovieById(req.params.id, (err, movie) => { if(err) return next(err); res.json(movie) }); }) } movies.js
  • 29. Server - Movies npm install supertest nano /cinema-microservice/movies- service/src/api/movies.test.js movies.test.js
  • 30. Server - Movies npm install supertest nano /cinema-microservice/movies- service/src/api/movies.test.js const test = require('tape'); const supertest = require('supertest'); const movies = require('./movies'); const server = require("../server/server"); const repository = require("../repository/repository"); movies.test.js
  • 31. Server - Movies function runTests(){ var app = null; server.start(movies, repository, (err, app) => { //tests here server.stop(); }) } module.exports = { runTests } movies.test.js
  • 32. Server - Movies var id = null; test('GET /movies', (t) => { supertest(app) .get('/movies') .expect('Content-Type', /json/) .expect(200) .end((err, res) =>{ if(res.body && res.body.length > 0) id = res.body[0]._id; t.assert(res.body && res.body.length > 0, "All Movies returned") t.end() }) }) movies.test.js
  • 33. Server - Movies test('GET /movies/:id', (t) => { if(!id) { t.assert(false, "Movie by Id Returned"); t.end(); return; } supertest(app) .get('/movies/' + id) .expect('Content-Type', /json/) .expect(200) .end((err, res) =>{ t.assert(res.body, "Movies By Idreturned") t.end() }) }) movies.test.js
  • 34. Server - Movies test('GET /movies/premieres', (t) => { supertest(app) .get('/movies/premieres') .expect('Content-Type', /json/) .expect(200) .end((err, res) =>{ t.assert(res.body && res.body.length > 0, "Premiere Movies returned") t.end() }) }) movies.test.js
  • 37. Index - Movies nano /cinema-microservice/movies-service/src/index.js require("dotenv-safe").load(); const movies = require('./api/movies'); const server = require("./server/server"); const repository = require("./repository/repository"); server.start(movies, repository, (err, app) => { console.log("just started"); }); index.js
  • 41. 1 Adicione busca por nome no microservice 2 Adicione paginação no getAllMovies 3 Adicione o restante do CRUD ao microservice