SlideShare una empresa de Scribd logo
1 de 42
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!

Más contenido relacionado

La actualidad más candente

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/OBuzzcapture
 
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 Tornadoemptysquare
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
RDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRDSDataSource: Мастер-класс по Dip
RDSDataSource: Мастер-класс по DipRAMBLER&Co
 
第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 themFilipe 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íncronasFilipe Ximenes
 
Python Yield
Python YieldPython Yield
Python Yieldyangjuven
 
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. NowKrzysztof 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 EffectsGlobalLogic Ukraine
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For BeginnersWilson Su
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS TestingEyal 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 BeastsFederico Galassi
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 

La actualidad más candente (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 a Node.js MongoDB Movies API & Microservice

Modules and injector
Modules and injectorModules and injector
Modules and injectorEyal 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 frameworkBen 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-2018Wim Selles
 
Automation in angular js
Automation in angular jsAutomation in angular js
Automation in angular jsMarcin 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 jsFrancois 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 KotlinDmitriy 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 HMRJavier Abadía
 
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 DjangoJavier 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 2013Laurent_VB
 
Владимир Мигуро "Дао 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 SagaBabacar NIANG
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen 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 2011Nick 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.jssoft-shake.ch
 

Similar a Node.js MongoDB Movies API & Microservice (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
 

Más de 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 MongoDBLuiz 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 PassoLuiz 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 07Luiz 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 04Luiz 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 02Luiz 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 03Luiz 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çãoLuiz 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 01Luiz 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 05Luiz 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 06Luiz Duarte
 
Carreira em Agilidade
Carreira em AgilidadeCarreira em Agilidade
Carreira em AgilidadeLuiz Duarte
 
Gamification em Modelos de Maturidade
Gamification em Modelos de MaturidadeGamification em Modelos de Maturidade
Gamification em Modelos de MaturidadeLuiz 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 - 20Luiz 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 - 19Luiz 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 - 18Luiz 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 - 17Luiz 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 - 15Luiz 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 - 14Luiz 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 - 13Luiz Duarte
 

Más de 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
 

Último

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Último (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Node.js MongoDB Movies API & Microservice

  • 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