You are viewing documentation for a beta release that is currently undergoing final testing before its official release. For the latest stable version click here.

Usage

Install Moleculer

Moleculer can be installed with npm or yarn.

$ npm i moleculer --save

Create your first microservice

This basic example shows how to create a small math service to add two numbers and call it locally.

const { ServiceBroker } = require("moleculer");

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

// Define a service
broker.createService({
name: "math",
actions: {
add(ctx) {
return Number(ctx.params.a) + Number(ctx.params.b);
}
}
});

// Start the broker
broker.start()
// Call the service
.then(() => broker.call("math.add", { a: 5, b: 3 }))
// Print the response
.then(res => console.log("5 + 3 =", res))
.catch(err => console.error(`Error occured! ${err.message}`));
Try it in your browser!

Open this example on Runkit!

Create a Moleculer project

In this example we use the official Moleculer CLI tool to create a new Moleculer-based microservices project with a sample service and an API Gateway to call it from the browser via REST API.

  1. Install moleculer-cli globally

    $ npm i moleculer-cli -g
  2. Create a new project (named moleculer-demo)

    $ moleculer init project moleculer-demo

    Press ENTER to all questions (accept default answers)

    Don’t forget to install and start NATS Server. Otherwise, you will get the following error:
    NATS error. Could not connect to server: Error: connect ECONNREFUSED 127.0.0.1:4222

  3. Open project folder

    $ cd moleculer-demo
  4. Start project

    $ npm run dev
  5. Open the http://localhost:3000/ link in your browser. It shows a start page which contains two links to call the greeter service via API gateway.

Congratulations!

You have just created your first Moleculer-based microservices project! Next, check out Moleculer’s core concepts page to get familiar with them and to see how they fit together. Otherwise, check our examples or demo projects.

You can also check the video below that explains ins and outs of the project that you’ve just created.

Moleculer Demo Playground

If you don’t want to install moleculer-demo on your machine you can use interactive playground.