The Talent500 Blog
How to Build Microservices with Node.js 1

How to Build Microservices with Node.js

Microservices are an architectural style that has gained popularity in recent years due to its ability to help build scalable and flexible systems. With this approach, applications are broken down into smaller, independent services that can be developed and deployed separately, allowing for faster iteration and better fault tolerance. Node.js, with its non-blocking I/O and lightweight runtime, is a great choice for building microservices. In this guide, we’ll explore the key concepts of microservices and show you how to build microservices with Node.js.

The blog will consist of simple steps that can be followed to start building your own demo app.

Microservices with Node.js Example

In this showcase application, we will use NodeJS to create microservices that will connect to an external API.

There will be three services in the app: Book, Customer, and Order. Individual servers will be running on various ports for each service. REST APIs will be used to communicate between these services. We are all aware that without microservices architecture, we would only have one server functioning. The situation is different with microservices architecture.

So, that’s what we’re developing in this lesson; now let’s get started with the code.

Initial Set-Up

Make sure you have Node.js installed if your system doesn’t have Node.js. To download the latest Node version, Visit Nodejs.org.

In the project root folder, run npm init. This will generate a package.json file with questions about the package; if you are unsure how to reply, use the default.

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

$ npm install express mongoose axios dotenv –save

Project Structure

The project structure is depicted in the graphic below. The structure might differ from one individual to the next.

Creating Database Connection

Let’s begin with the fundamental step of establishing a database connection. Create a db.js file in the db subdirectory to code the database connection. This is simply a modest example project, but larger and more complicated systems use separate databases for each service.

// db.js

const mongoose = require(‘mongoose’);

mongoose.connect(process.env.MONGO_URI, { 

     useNewUrlParser: true,

     useUnifiedTopology: true,

     useFindAndModify: false,

     useCreateIndex: true

}).then(() => {

     console.log(‘Connection successful!’);

}).catch((e) => {

     console.log(‘Connection failed!’);

})


For a MongoDB database connection, we must use the mongoose package in db.js.

The connect() method will accept two arguments: uri and options.

Creating Book Service

Make a Book folder for the Book service, and inside it, make Book.js to create a Book Model.

// Book.js

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

   }

})

const Book = mongoose.model(“book”, bookSchema);
module.exports = Book;

Now we must set up a server for the Book service.

Create a Server for Book Service

Create a file called books.js in the Book folder. We will have different servers for services as we learn to create microservices.

// 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((book) => {

        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`);
})


Here we have to create a server with express, create the db file necessary for connecting to the database, and utilised the Book model to store data.

There are four routes in Book service:

  • Add books
  • Get all the books from the database
  • Get a particular book
  • Delete a book

Book service needs to be Run at port 3000.

Creating Customer Service

Set up a Customer folder for Customer service, and within that folder, place Customer. JavaScript for model, like we done in the previous part for Book service.

// Customer.js

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;


Now we must set up a server for customer service.

Create a Server for Customer Service

We will also have a dedicated server for customer assistance. Create a file called 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((customer) => {

     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`);
})


Build the same four customer service routes that we created for the Book service.

Run Customer service at port 5000.

Creating Order Service

For model, create an Order.js file in the Order folder, much like we did for Book and Customer service.

// Order.js

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

     }

})

const Order = mongoose.model(“order”, orderSchema);
module.exports = Order;

Now we must set up a server for the Order service.

Create a Server for Order Service

Inside the Order folder, create order.js.

// order.js

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.customerID),

   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/${order.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`);
})


Run the customer service at port 9000.

 

In Order service, we will create three routes:

  • Add an order. We have to pass bookId, customerId, initialDate, and deliveryDate for it.
  • Get all the orders from the database
  • Get customers and booking details for a certain order.

To run the final route, ensure that all services are functioning in the background. Since we are receiving information from both book service and customer service.

Conclusion

Every service is independently deployable, scalable, and updatable in microservices which makes microservices an attractive way to build in the industry. Microservices are freely integrated and integrate with other microservices of well-defined systems via protocols such as http, and they remain stable and available in the event of a failure, which means that even if the machine holding the microservice fails, the service must still be provided by the app. We hope your visit to the instructional fulfils the purpose you anticipated. Clone the repository and experiment with the code to create Node.js microservices.

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment