What are Microservices and Molecular in NodeJS?
Microservices is an approach to software development where software complies with multiple independent services that communicate with the APIs.
Microservices architectures increase the scalability of the application and also make it easy to develop.
Monolithic Architecture vs. Microservices Architecture
Monolithic is the traditional architecture where all the functionalities of the software are tightly coupled, which has many drawbacks like following :
  • Scalability: As the application grows, it will require more CPU power and memory, which also increases the load on the server.
  • Deployment: Even a minute change requires redeploying the entire application.
To avoid these issues we use Microservices. Molecular is the nodeJS framework to create Microservices.Diagram comparing monolithic vs. microservices architecture
How to install ?
npm i moleculer moleculer-web
OR
yarn add moleculer moleculer-web
Create a sample microservice
Following is the sample code which create the service which handles the get request and returns the json response with message.
const { ServiceBroker } = require("moleculer");
const ApiGateway = require("moleculer-web");

// Create a Service Broker
const broker = new ServiceBroker();

// Create the API Gateway Service
broker.createService({
  name: "api",
  mixins: [ApiGateway],
  actions: {
    handleReq(ctx) {
      return {status:true,message:"Request recieved"};
    },
  },
  settings: {
    port: 3000,
    routes: [
      {
        path: "/",
        aliases: {
          "GET /": "api.handleReq"
        },
      }
    ],
  }
});

// Start the broker with error handling
broker.start()
  .then(() => {
    console.log("API Gateway running at http://localhost:3000/");
  })
  .catch(err => {
    console.error(`Error occurred while starting the broker: ${err.message}`);
    process.exit(1);
  });
Output of the above code :
{
  "status": true,
  "message": "Request recieved"
}
Explaination of the code :
Importing dependencies :
const { ServiceBroker } = require("moleculer");
const ApiGateway = require("moleculer-web");
  • ServiceBroker: This is the core of Moleculer. It is responsible for creating services, handling service calls, managing service discovery, and more.
  • ApiGateway: This is a Moleculer mixin that provides web server functionality to expose services over HTTP.
Create the Service Broker :
const broker = new ServiceBroker();
Create the API Gateway Service :
broker.createService({
    name: "api",
    mixins: [ApiGateway],
    actions: {
      handleReq(ctx) {
        return { status: true, message: "Request received" };
      },
    },
    settings: {
      port: 3000,
      routes: [
        {
          path: "/",
          aliases: {
            "GET /": "api.handleReq",
          },
          mappingPolicy: "restrict",
        },
      ],
      cors: {
        origin: "*",
        methods: ["GET", "OPTIONS", "POST", "PUT", "DELETE"],
      },
    },
  });
  • name:"api": This specifies the name of the service.
  • mixins: [ApiGateway]: This indicates that the service will use the ApiGateway mixin, enabling it to act as an HTTP server.
  • actions: This section defines the actions (or methods) that the service exposes.
  • handleReq(ctx): An action named handleReq that returns a JSON response with a status and message.
  • settings: Configuration settings for the service.
  • port:3000: Specifies the port on which the API Gateway will listen.
  • routes: Defines the routes that the API Gateway will handle.
  • path: Specifies the base path for the routes.
  • aliases: Maps HTTP methods and paths to service actions.
  • GET /: "api.handleReq": Maps a GET request to the root path ("/") to the handleReq action.
To learn more you can follow the official document https://moleculer.services/docs

- Uploaded by Tanay kulkarni
  Date: 11th July 2024
Related Blogs
The beginner's guide to creating react component
Read
Beginner's guide for creating ORM in Node.JS? | What is Sequelize in Node.JS?
Read
© All Rights Reserved to Tanay Kulkarni