Microservice from Scratch (3): Write the microservice template

Ninh Nguyen
2 min readDec 21, 2021

--

In this article, we will build a template microservice which defined all directories, settings and some necessary files. It will save a lot of time when we need to create a new service for our project.

Initial Project

Firstly, we need to create new directory and initialize new NodeJS project:

mkdir bs-base-service && cd bs-base-service
npm init -y

Then, install necessary packages:

npm install -y body-parser dotenv mongoose thebigdev-microservicenpm install -y -save-dev mocha nodemon supertest

In this series, mongoDB will be used as the main database, so we will install mongoose library to define schema and access to the database.

Project Directories

  • config: we define all code which need to run before we start the application. In this series, we only use it to connect to database, but you can use it to start the code for logging, redis, etc
  • middleware: contain Express middleware for this micro-service.
  • routes: as the name of it, we will define all routes for each micro-service.
  • models: we will define all schema to access the persistent data, such as a database, redis server, etc.
  • controllers: each route will have an unique controller to handle the request. It doesn’t contain any logic other than calling the service.
  • services: contain the majority of the business logic. It can call the models, other API’s external, or algorithmic code.
  • .env: we will use dotenv library to import all settings from .env file. I prefer it because it will expand process.env object, so we can pass them to “thebigdev-microservice” package.
  • helpers (optional): contain helper functions for your project.

You can see all code in my github.

How to use?

Now, when we need to create a new microserice, we only need to run few commands to clone it:

$ git clone https://github.com/ninhnt285/bs-base-service.git bs-new-service && cd bs-new-service
$ npm install
$ cp .env.bak .env
$ git remote set-url origin new-repo-url
$ git push

That’s too fast and easy. :)

Next Step

In the next tutorial, we will start to write the first microservice bs-user-service to resolve all request to auth, manage users.

--

--

Ninh Nguyen
Ninh Nguyen

No responses yet