SlideShare a Scribd company logo
How to Build
Microservices
with Node.js
www.bacancytechnology.com
Divide into independent chunks to build the
entire application.
Introduction
In the last blog, we learned about
Microservice Architecture and Why Build
Microservices with Node.js. If you haven’t
explored or read much about Microservice
Architecture then I would recommend
visiting our last blog, to have basic
theoretical knowledge. The blog deals with
What, Why, and When with Microservices.
We will cover the remaining question ‘How’
in this tutorial.


You are exactly right! In this tutorial, we
will learn how to build a basic demo
application for illustrating Microservices
with Node.js. The tutorial will consist of
basic and simple steps that you can follow
with us and start building your own demo
app.


Without further ado, let’s get started with
our application.
Microservices
with Node.js
Example
In this demo application, we will build
microservices with NodeJS which will
connect to an external API.


The app will have three services: Book,
Customer, and Order services. Each of the
services will have individual servers
running on different ports. These services
will communicate with each other through
REST APIs. We all know that if it wasn’t
microservices architecture we would have
only one server running. But, in
microservices architecture the scenario is
different.


So, this was about what we are building in
this tutorial, let’s get started with the
coding part.
Initial Set-Up
Make sure you have Node.js installed. Visit
Nodejs.org to download the latest Node
version, if your system doesn’t have
Node.js.


Run npm init in the project root folder. This
will create a package.json file that will
create certain questions about the package,
if you are not sure how to respond you can
use the default.


We will use four packages, Express,
mongoose, axios, and dotenv which can be
installed as follows:


$ npm install express mongoose axios
dotenv --save
Project Structure
Refer to the below image for the project
structure. The structure can vary from
person to person.
Creating
Database
Connection
Let’s start with the basic step to establish a
DB connection. In the db folder, create a
db.js to code to connect the database. This is
just a small demo app, but the large and
complex applications also have different
databases for individual services.
// db.js
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_U
RI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
}).then(() => {
console.log('Connection successful!');
}).catch((e) => {
console.log('Connection failed!');
})
In db.js, we have to require a mongoose
package for MongoDB database connection.


The function connect() will take two
arguments – uri and options.
Creating Book
Service
const mongoose = require('mongoose');
const bookSchema = mongoose.Schema({
title: {
type: String,
require: true
},
author: {
type: String,
require: true
},
numberPages: {
type: Number,
require: false
},
publisher: {
type: String,
require: false
Create a Book folder for Book service, inside
the Book folder we will create Book.js for
creating a Book Model.
// Book.js
}
})
const Book = mongoose.model("book",
bookSchema);
module.exports = Book;


Now we will need to create a server for the
Book service.
Create a Server for Book
Service
Create books.js inside the Book folder. Since
we are learning to build microservices we
will have different servers for services.


// books.js
require("dotenv").config();
const express = require('express');
// Connect
require('../db/db');
const Book = require('./Book');
const app = express();
const port = 3000;
app.use(express.json())
app.post('/book', (req, res) => {
const newBook = new Book({...req.body});
newBook.save().then(() => {
res.send('New Book added successfully!')
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
})
})
app.get('/books', (req, res) => {
Book.find().then((books) => {
if (books.length !== 0) {
res.json(books)
} else {
res.status(404).send('Books not found');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
})
app.get('/book/:id', (req, res) => {
Book.findById(req.params.id).then((book)
=> {
if (book) {
res.json(book)
} else {
res.status(404).send('Books not found');
}
}).catch((err) => {
res.status(500).send('Internal Server Error!');
});
})
app.delete('/book/:id', (req, res) => {
Book.findOneAndRemove(req.params.id).then((b
ook) => {
if (book) {
res.json('Book deleted Successfully!')
} else {
res.status(404).send('Book Not found!');
}
}).catch((err) => {
res.status(500).send('Internal Server Error!');
});
});
app.listen(port, () => {
console.log(`Up and Running on port ${port} -
This is Book service`);
})
Add books
Get all the books from the database
Get a particular book
Delete a book
We have used express for creating a server,
made the db file required for connecting
with the database, and Book model for
storing data.


The Book service has four routes:


Run book service at port 3000.
Creating
Customer
Service
const mongoose = require('mongoose');
const CustomerSchema = mongoose.Schema({
name: {
type: String,
require: true
},
age: {
type: Number,
require: true
},
address: {
type: String,
require: true
}
})
const Customer = mongoose.model("customer",
CustomerSchema);
module.exports = Customer;
Create a Customer folder for Customer
service, inside the Customer folder we will
have Customer.js for model, just like we did
for Book service in the previous section.
// Customer.js
Now we will need to create a server for
Customer service.
Create a Server for
Customer Service
We will have a separate server for Customer
service as well. Create a file named
customer.js.
// customer.js
require("dotenv").config();
const express = require('express');
// Connect
require('../db/db');
const Customer = require('./Customer');
const app = express();
const port = 5000;
app.use(express.json())
app.post('/customer', (req, res) => {
const newCustomer = new
Customer({...req.body});
newCustomer.save().then(() => {
res.send('New Customer created
successfully!');
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
})
})
app.get('/customers', (req, res) => {
Customer.find().then((customers) => {
if (customers) {
res.json(customers)
} else {
res.status(404).send('customers not found');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
})
app.get('/customer/:id', (req, res) => {
Customer.findById(req.params.id).then((cu
stomer) => {
if (customer) {
res.json(customer)
} else {
res.status(404).send('customer not found');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
})
app.delete('/customer/:id', (req, res) => {
Customer.findByIdAndRemove(req.params.
id).then((customer) => {
if (customer) {
res.json('customer deleted Successfully!')
} else {
res.status(404).send('Customer Not
Found!');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
});
app.listen(port, () => {
console.log(`Up and Running on port
${port}- This is Customer service`);
})
Create the same four routes for Customer
service as we did for the Book service


Run Customer service at port 5000.
Creating
Order Service
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
customerID: {
type: mongoose.SchemaTypes.ObjectId,
require: true
},
bookID: {
type: mongoose.SchemaTypes.ObjectId,
require: true
},
initialDate: {
type: Date,
require: true
},
deliveryDate: {
type: Date,
require: false
// Order.js
Create an Order.js file inside the Order
folder for model, just like we did for Book
and Customer service.
}
})
const Order = mongoose.model("order",
orderSchema);
module.exports = Order;


Now we will need to create a server for the
Order service.


Create a Server for Order
Service
Create order.js inside the Order folder.
require("dotenv").config();
const express = require('express');
const mongoose = require("mongoose");
const axios = require('axios');
// Connect
require('../db/db');
const Order = require('./Order');
const app = express();
const port = 9000;
app.use(express.json())
app.post('/order', (req, res) => {
const newOrder = new Order({
customerID:
mongoose.Types.ObjectId(req.body.custom
erID),
// order.js
bookID:
mongoose.Types.ObjectId(req.body.bookID)
,
initialDate: req.body.initialDate,
deliveryDate: req.body.deliveryDate
});
newOrder.save().then(() => {
res.send('New order added successfully!')
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
})
})
app.get('/orders', (req, res) => {
Order.find().then((orders) => {
if (orders) {
res.json(orders)
} else {
res.status(404).send('Orders not found');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
})
app.get('/order/:id', (req, res) => {
Order.findById(req.params.id).then((order)
=> {
if (order) {
axios.get(`http://localhost:5000/customer/
${order.customerID}`).then((response) => {
let orderObject = {
CustomerName: response.data.name,
BookTitle: ''
}
axios.get(`http://localhost:3000/book/${ord
er.bookID}`).then((response) => {
orderObject.BookTitle = response.data.title
res.json(orderObject);
})
})
} else {
res.status(404).send('Orders not found');
}
}).catch((err) => {
res.status(500).send('Internal Server
Error!');
});
})
app.listen(port, () => {
console.log(`Up and Running on port
${port} - This is Order service`);
})
Add an order. You need to pass bookId,
customerId, initialDate, and
deliveryDate for it.
Get all the orders from the database
Get customers and book details for a
particular order.
Run customer service at port 9000.


We will create three routes in Order service:
To run the last route make sure all the
services are running in the background.
Because we are getting details from book
service and customer service as well.


So, this was a step-by-step guide to build
microservices with Node.js. The entire
source code is available here: nodejs-
microservices-example
Conclusion
In microservices, every service is
independently deployable, scalable, and
updatable, which is what makes
microservices an attractive way to build in
the industry.


Microservice is freely integrated and
integrates with other microservices of well-
defined systems using protocols such as
http, they remain stable and available in the
event of a failure, which means that even if
the machine goes down to hold the
microservice, the service provided must
still be supplied by the app.


I hope your purpose for visiting the tutorial
has served the way you’ve expected. Feel free
to clone the repository and play around with
the code to build microservices with Node.js.
If you want to learn more about Node.js, visit
Node.js tutorials page where you are provided
with step-by-step instructions to build demo
apps and github repositories.
Are you looking for a helping hand for your
NodeJS project? Do you need skilled and
dedicated developers with NodeJS
expertise? Then without wasting a second,
contact us and hire NodeJs developers.
Thank You
www.bacancytechnology.com

More Related Content

PDF
Microservices in Node.js: Patterns and techniques
PPTX
Dependency injection - the right way
PPTX
Operators in java
PDF
Ethereum Solidity Fundamentals
PDF
MongoDB and Node.js
PDF
Clean Architecture
PPTX
Exception handling.pptx
PDF
Programação Desktop: Uma abordagem com Java
Microservices in Node.js: Patterns and techniques
Dependency injection - the right way
Operators in java
Ethereum Solidity Fundamentals
MongoDB and Node.js
Clean Architecture
Exception handling.pptx
Programação Desktop: Uma abordagem com Java

What's hot (20)

PDF
Javascript Design Patterns
PPT
Looping in C
PDF
Introduction to ASP.NET Core
PDF
Intermediate code generation
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PPT
Formation jpa-hibernate-spring-data
PDF
Clean code
PDF
Développement d'applications pour la plateforme Java EE
PDF
C# ASP.NET WEB API APPLICATION DEVELOPMENT
PPTX
Pandas csv
PPT
Operators in C++
PPTX
Introduction to Django
PPTX
Introduction to Node js
PDF
C# Dot net unit-2.pdf
PPTX
Spring Framework
PPTX
Javax.servlet,http packages
PPTX
Dependency injection presentation
PDF
Long running processes in DDD
PPT
Coding theory updated
Javascript Design Patterns
Looping in C
Introduction to ASP.NET Core
Intermediate code generation
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Formation jpa-hibernate-spring-data
Clean code
Développement d'applications pour la plateforme Java EE
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Pandas csv
Operators in C++
Introduction to Django
Introduction to Node js
C# Dot net unit-2.pdf
Spring Framework
Javax.servlet,http packages
Dependency injection presentation
Long running processes in DDD
Coding theory updated
Ad

Similar to How to build microservices with node.js (20)

PDF
Node.js Microservices Building Scalable and Reliable Applications.pdf
PDF
Basic API Creation with Node.JS
PDF
Writing RESTful web services using Node.js
PPTX
Node js crash course session 5
PDF
Divide and Conquer – Microservices with Node.js
PDF
TDD a REST API With Node.js and MongoDB
PDF
Developing and Testing a MongoDB and Node.js REST API
PPTX
Unit IV database intergration with node js
PPTX
Webinar: Get Started with the MEAN Stack
PDF
MEAN Stack WeNode Barcelona Workshop
PDF
All-inclusive insights on Building JavaScript microservices with Node!.pdf
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
PPTX
Develop a Basic REST API from Scratch Using TDD with Val Karpov
PDF
MongoDB MEAN Stack Webinar October 7, 2015
PDF
Getting started with node JS
PPTX
Local SQLite Database with Node for beginners
PPTX
Zero to Hipster with the M.I.K.E. Stack
PDF
Backend Basic in nodejs express and mongodb PPT.pdf
PDF
Introduction to REST API with Node.js
PPT
nodejs tutorial foor free download from academia
Node.js Microservices Building Scalable and Reliable Applications.pdf
Basic API Creation with Node.JS
Writing RESTful web services using Node.js
Node js crash course session 5
Divide and Conquer – Microservices with Node.js
TDD a REST API With Node.js and MongoDB
Developing and Testing a MongoDB and Node.js REST API
Unit IV database intergration with node js
Webinar: Get Started with the MEAN Stack
MEAN Stack WeNode Barcelona Workshop
All-inclusive insights on Building JavaScript microservices with Node!.pdf
Develop a Basic REST API from Scratch Using TDD with Val Karpov
Develop a Basic REST API from Scratch Using TDD with Val Karpov
MongoDB MEAN Stack Webinar October 7, 2015
Getting started with node JS
Local SQLite Database with Node for beginners
Zero to Hipster with the M.I.K.E. Stack
Backend Basic in nodejs express and mongodb PPT.pdf
Introduction to REST API with Node.js
nodejs tutorial foor free download from academia
Ad

More from Katy Slemon (20)

PDF
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
PDF
Data Science Use Cases in Retail & Healthcare Industries.pdf
PDF
How Much Does It Cost To Hire Golang Developer.pdf
PDF
What’s New in Flutter 3.pdf
PDF
Why Use Ruby On Rails.pdf
PDF
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
PDF
How to Implement Middleware Pipeline in VueJS.pdf
PDF
How to Build Laravel Package Using Composer.pdf
PDF
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
PDF
How to Develop Slack Bot Using Golang.pdf
PDF
IoT Based Battery Management System in Electric Vehicles.pdf
PDF
Understanding Flexbox Layout in React Native.pdf
PDF
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
PDF
New Features in iOS 15 and Swift 5.5.pdf
PDF
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
PDF
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
PDF
Flutter Performance Tuning Best Practices From the Pros.pdf
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
PDF
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
PDF
Ruby On Rails Performance Tuning Guide.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
How Much Does It Cost To Hire Golang Developer.pdf
What’s New in Flutter 3.pdf
Why Use Ruby On Rails.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How to Implement Middleware Pipeline in VueJS.pdf
How to Build Laravel Package Using Composer.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
How to Develop Slack Bot Using Golang.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Understanding Flexbox Layout in React Native.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
New Features in iOS 15 and Swift 5.5.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Ruby On Rails Performance Tuning Guide.pdf

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
KodekX | Application Modernization Development
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Chapter 3 Spatial Domain Image Processing.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

How to build microservices with node.js

  • 1. How to Build Microservices with Node.js www.bacancytechnology.com
  • 2. Divide into independent chunks to build the entire application.
  • 4. In the last blog, we learned about Microservice Architecture and Why Build Microservices with Node.js. If you haven’t explored or read much about Microservice Architecture then I would recommend visiting our last blog, to have basic theoretical knowledge. The blog deals with What, Why, and When with Microservices. We will cover the remaining question ‘How’ in this tutorial. You are exactly right! In this tutorial, we will learn how to build a basic demo application for illustrating Microservices with Node.js. The tutorial will consist of basic and simple steps that you can follow with us and start building your own demo app. Without further ado, let’s get started with our application.
  • 6. In this demo application, we will build microservices with NodeJS which will connect to an external API. The app will have three services: Book, Customer, and Order services. Each of the services will have individual servers running on different ports. These services will communicate with each other through REST APIs. We all know that if it wasn’t microservices architecture we would have only one server running. But, in microservices architecture the scenario is different. So, this was about what we are building in this tutorial, let’s get started with the coding part.
  • 8. Make sure you have Node.js installed. Visit Nodejs.org to download the latest Node version, if your system doesn’t have Node.js. Run npm init in the project root folder. This will create a package.json file that will create certain questions about the package, if you are not sure how to respond you can use the default. We will use four packages, Express, mongoose, axios, and dotenv which can be installed as follows: $ npm install express mongoose axios dotenv --save
  • 9. Project Structure Refer to the below image for the project structure. The structure can vary from person to person.
  • 11. Let’s start with the basic step to establish a DB connection. In the db folder, create a db.js to code to connect the database. This is just a small demo app, but the large and complex applications also have different databases for individual services. // db.js const mongoose = require('mongoose'); mongoose.connect(process.env.MONGO_U RI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }).then(() => { console.log('Connection successful!'); }).catch((e) => { console.log('Connection failed!'); })
  • 12. In db.js, we have to require a mongoose package for MongoDB database connection. The function connect() will take two arguments – uri and options.
  • 14. const mongoose = require('mongoose'); const bookSchema = mongoose.Schema({ title: { type: String, require: true }, author: { type: String, require: true }, numberPages: { type: Number, require: false }, publisher: { type: String, require: false Create a Book folder for Book service, inside the Book folder we will create Book.js for creating a Book Model. // Book.js
  • 15. } }) const Book = mongoose.model("book", bookSchema); module.exports = Book; Now we will need to create a server for the Book service.
  • 16. Create a Server for Book Service Create books.js inside the Book folder. Since we are learning to build microservices we will have different servers for services. // books.js require("dotenv").config(); const express = require('express'); // Connect require('../db/db'); const Book = require('./Book'); const app = express(); const port = 3000; app.use(express.json()) app.post('/book', (req, res) => { const newBook = new Book({...req.body});
  • 17. newBook.save().then(() => { res.send('New Book added successfully!') }).catch((err) => { res.status(500).send('Internal Server Error!'); }) }) app.get('/books', (req, res) => { Book.find().then((books) => { if (books.length !== 0) { res.json(books) } else { res.status(404).send('Books not found'); } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }) app.get('/book/:id', (req, res) => { Book.findById(req.params.id).then((book) => {
  • 18. if (book) { res.json(book) } else { res.status(404).send('Books not found'); } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }) app.delete('/book/:id', (req, res) => { Book.findOneAndRemove(req.params.id).then((b ook) => { if (book) { res.json('Book deleted Successfully!') } else { res.status(404).send('Book Not found!'); } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }); app.listen(port, () => { console.log(`Up and Running on port ${port} - This is Book service`); })
  • 19. Add books Get all the books from the database Get a particular book Delete a book We have used express for creating a server, made the db file required for connecting with the database, and Book model for storing data. The Book service has four routes: Run book service at port 3000.
  • 21. const mongoose = require('mongoose'); const CustomerSchema = mongoose.Schema({ name: { type: String, require: true }, age: { type: Number, require: true }, address: { type: String, require: true } }) const Customer = mongoose.model("customer", CustomerSchema); module.exports = Customer; Create a Customer folder for Customer service, inside the Customer folder we will have Customer.js for model, just like we did for Book service in the previous section. // Customer.js
  • 22. Now we will need to create a server for Customer service. Create a Server for Customer Service We will have a separate server for Customer service as well. Create a file named customer.js. // customer.js require("dotenv").config(); const express = require('express'); // Connect require('../db/db'); const Customer = require('./Customer'); const app = express(); const port = 5000; app.use(express.json())
  • 23. app.post('/customer', (req, res) => { const newCustomer = new Customer({...req.body}); newCustomer.save().then(() => { res.send('New Customer created successfully!'); }).catch((err) => { res.status(500).send('Internal Server Error!'); }) }) app.get('/customers', (req, res) => { Customer.find().then((customers) => { if (customers) { res.json(customers) } else { res.status(404).send('customers not found'); } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); })
  • 24. app.get('/customer/:id', (req, res) => { Customer.findById(req.params.id).then((cu stomer) => { if (customer) { res.json(customer) } else { res.status(404).send('customer not found'); } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }) app.delete('/customer/:id', (req, res) => { Customer.findByIdAndRemove(req.params. id).then((customer) => { if (customer) { res.json('customer deleted Successfully!') } else { res.status(404).send('Customer Not Found!');
  • 25. } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }); app.listen(port, () => { console.log(`Up and Running on port ${port}- This is Customer service`); }) Create the same four routes for Customer service as we did for the Book service Run Customer service at port 5000.
  • 27. const mongoose = require('mongoose'); const orderSchema = mongoose.Schema({ customerID: { type: mongoose.SchemaTypes.ObjectId, require: true }, bookID: { type: mongoose.SchemaTypes.ObjectId, require: true }, initialDate: { type: Date, require: true }, deliveryDate: { type: Date, require: false // Order.js Create an Order.js file inside the Order folder for model, just like we did for Book and Customer service.
  • 28. } }) const Order = mongoose.model("order", orderSchema); module.exports = Order; Now we will need to create a server for the Order service. Create a Server for Order Service Create order.js inside the Order folder.
  • 29. require("dotenv").config(); const express = require('express'); const mongoose = require("mongoose"); const axios = require('axios'); // Connect require('../db/db'); const Order = require('./Order'); const app = express(); const port = 9000; app.use(express.json()) app.post('/order', (req, res) => { const newOrder = new Order({ customerID: mongoose.Types.ObjectId(req.body.custom erID), // order.js
  • 30. bookID: mongoose.Types.ObjectId(req.body.bookID) , initialDate: req.body.initialDate, deliveryDate: req.body.deliveryDate }); newOrder.save().then(() => { res.send('New order added successfully!') }).catch((err) => { res.status(500).send('Internal Server Error!'); }) }) app.get('/orders', (req, res) => { Order.find().then((orders) => { if (orders) { res.json(orders) } else { res.status(404).send('Orders not found'); } }).catch((err) => { res.status(500).send('Internal Server Error!');
  • 31. }); }) app.get('/order/:id', (req, res) => { Order.findById(req.params.id).then((order) => { if (order) { axios.get(`http://localhost:5000/customer/ ${order.customerID}`).then((response) => { let orderObject = { CustomerName: response.data.name, BookTitle: '' } axios.get(`http://localhost:3000/book/${ord er.bookID}`).then((response) => { orderObject.BookTitle = response.data.title res.json(orderObject); }) }) } else { res.status(404).send('Orders not found');
  • 32. } }).catch((err) => { res.status(500).send('Internal Server Error!'); }); }) app.listen(port, () => { console.log(`Up and Running on port ${port} - This is Order service`); }) Add an order. You need to pass bookId, customerId, initialDate, and deliveryDate for it. Get all the orders from the database Get customers and book details for a particular order. Run customer service at port 9000. We will create three routes in Order service:
  • 33. To run the last route make sure all the services are running in the background. Because we are getting details from book service and customer service as well. So, this was a step-by-step guide to build microservices with Node.js. The entire source code is available here: nodejs- microservices-example
  • 35. In microservices, every service is independently deployable, scalable, and updatable, which is what makes microservices an attractive way to build in the industry. Microservice is freely integrated and integrates with other microservices of well- defined systems using protocols such as http, they remain stable and available in the event of a failure, which means that even if the machine goes down to hold the microservice, the service provided must still be supplied by the app. I hope your purpose for visiting the tutorial has served the way you’ve expected. Feel free to clone the repository and play around with the code to build microservices with Node.js. If you want to learn more about Node.js, visit Node.js tutorials page where you are provided with step-by-step instructions to build demo apps and github repositories.
  • 36. Are you looking for a helping hand for your NodeJS project? Do you need skilled and dedicated developers with NodeJS expertise? Then without wasting a second, contact us and hire NodeJs developers.