Moleculer Header courtesy of MoleculerJs

A simple introduction

About Moleculer

As you may already know, Moleculer is a new and promising “progressive microservices framework for Node.js” that showcases a structure inspired by Vue.js, the famous JavaScript framework for building front ends. Due to its nice design, it feels very comfortable to architect software around microservices or to create general purpose Node.js restful APIs.

You can read more about Moleculer concepts in the official documentation.

A simple API

There are many frameworks that we can use to create API’s in Nodejs, but Moleculer is a kind of new kid on the block (you’ll love its Vue.js inspired architecture).

Before everything, you need to install Moleculer CLI by running the following command in your favourite console (you would also need Node.js):

npm install -g moleculer-cli

Now scaffold a Moleculer project (I called it “simple-project”, but feel free to choose whatever name you like) by running:

moleculer init project simple-project

Scaffolding process will ask you a few questions on the way, and if you don’t know what to choose, have a look at the example below (say No to the “Would you like to communicate with other nodes” question if you are at the beginning of your journey):

Template repo: moleculerjs/moleculer-template-project
? Add API Gateway (moleculer-web) service? Yes
? Would you like to communicate with other nodes? No
? Would you like to use cache? No
? Add Docker files? No
? Use ESLint to lint your code? No
? Setup unit tests with Jest? No
Create 'simple-project' folder...
? Would you like to run 'npm install'? Yes

For simplicity, I kept the project features at minimum, but I expect that for a real-life scenario you’ll be more picky with the options.

Scaffolding creates a folder called “simple-project” with the content you can see in the screenshot below (Visual Code explorer).

The CLI tool scaffolds a default greeter.service.js with two endpoints as you can see in the next Gist.

To see it in action, run the following command from within the project’s root folder (and don’t forget to call npm install if you haven’t done it yet).

npm install // If you haven't done it at the end of scaffolding
npm run dev

After Moleculer runner has started the API, access the following two locations from your favourite browser (or from Postman if you wish to have more control over the requests):

Congratulations, you have just created and launched your first Moleculer restful API.

You can also check a live version of a basic Moleculer project at Code Sandbox:

More Tutorials

  1. Moleculer Mixins
  2. Moleculer Routing
  3. How to host Moleculer in Firebase

Another short list of tutorials can be found on the blog maintained by Icebob (the original author of the framework).

Enjoy!

Software Developer