# Microservices with Node.js and Express

Source: https://lean-coders.at/en/blog/microservices-with-nodejs-and-express

> How to build a lightweight microservice architecture with Node.js and Express

Tags: backend · Published: 2022-08-24

Microservices with Node.js are a fantastic way to manage your backend - using the same code base that powers your frontend. 
Let's dive into the details of setting up a lightweight yet fle

##### What it's all about

Microservices with Node.js are a fantastic way to manage your backend - using the same code base that powers your frontend.

Let's dive into the details of setting up a lightweight yet flexible microservice architecture that scales and provides production resilience to your services.

All code samples in this blog post are available in the repo, so if you're in a hurry, head over to [https://github.com/lean-forge/microservices-nodejs-express](https://github.com/lean-forge/microservices-nodejs-express), clone it, and get started.

_Info: This blog post does not cover_ [NestJS](https://nestjs.com/)_. So if you're looking for a quick start with NestJS, I highly recommend_ [NestJS First Steps](https://docs.nestjs.com/first-steps) _series._

##### The stack

In this blog post, we focus on:

- [Node.js](https://nodejs.org/)
- [Express](https://expressjs.com/)
- [TypeScript](https://www.typescriptlang.org/)
- [TSyringe](https://github.com/microsoft/tsyringe)

As you may have already noticed: The focus of this article is to provide a lightweight microservice scaffold that you can use right away and that ensures a scalable yet simple architecture. So let's take a look.

##### The beginning

We start off with a very simple Node.js app with express routes - nothing new. You can find the code with commit ID [abe1fb7](https://github.com/lean-forge/microservices-nodejs-express/tree/abe1fb7e271c4d8794c29398cd0a827e943c253f).

We implemented a (very) basic CartController:

```
import express, { Request, Response } from "express"; 

export const CartController = express.Router(); 

CartController.post("/", (_req: Request, res: Response) => { 
   res.send("CartController.post");
}); 

CartController.get("/", (_req: Request, res: Response) => { 
   res.send("CartController.get");
});
```

Additionally, we prepared an interface IDataSource that is used in the MongoDBService - a simple but often-used dependency:

```
import { IDataSource } from "./DataSource"; 

export default class MongoDBService implements IDataSource {}
```

So here comes the first challenge: How can we improve code quality with this relationship? A very popular - and de-facto standard - choice to decouple this relationship is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). Don't get me wrong - there is nothing wrong with this implementation. When it comes to testing, it might get tricky. And dependency injection can help with that. Let's see how:

##### The improvements

For a full list of changes, please refer to commit [4853d10](https://github.com/lean-forge/microservices-nodejs-express/commit/4853d1025785ba8d01bd4b2ffe3a9674b389386a) for a detailed list of files (package-lock.json, package.json, etc.) - I will focus just on the relevant ones here.

Let's add **tsyringe** and **jest** to enable Dependency Injection with TypeScript and a testing framework.

The first thing to note is that by using tsyringe, we need to:

```
import 'reflect-metadata';
```

in **app.ts** as tsyringe as "the Reflect polyfill should be added once, and before DI is used". For detailed installation instructions, refer to the [tsyringe GitHub page](https://github.com/microsoft/tsyringe).

After integrating tsyringe, we are ready to actually make use of Dependency Injection:

```
import express, { Request, Response } from "express";
import { container } from "tsyringe";
import MongoDBService from "../datasource/MongoDBService";

export const CartController = express.Router();

CartController.post("/", (_req: Request, res: Response) => {
  res.send("CartController.post");
});

CartController.get("/", (_req: Request, res: Response) => {
    const db = container.resolve(MongoDBService);
    console.log(db.getAllItems());
    res.send("CartController.get");
});
```

In **CartController.ts** we integrate the _MongoDBService_-resolution via the tsyringe container. This enables us to replace the MongoDBService during testing with different mocks, as we will see in a minute - and is the key benefit of using Dependency Injection in apps.

Let's see what we changed to enable the MongoDBService resolution via the tsyringe container:

At first, we added an @injectable() DataSource class that implements the IDataSource interface:

```
import { injectable } from "tsyringe";
import { CartItem } from "../models/CartItem";

export interface IDataSource {
    getAllItems(): CartItem[];
};

@injectable()
export class DataSource implements IDataSource{
    getAllItems(): CartItem[] {
        return [];
    }
}

```

With the **@injectable** attribute - more accurately: a class decorator factory - tsyringe registers this class to be injectable at runtime. TSyringe relies on several decorators; to get to know all of them, refer to the TSyringe [GitHub page](https://github.com/microsoft/tsyringe).

The same attribute is applied to the MongoDBService class:

```
import { injectable } from "tsyringe";
import { CartItem } from "../models/CartItem";
import { DataSource } from "./DataSource";

@injectable()
export default class MongoDBService {
  constructor(database: DataSource) {
    this.database = database;
  }

  private database: DataSource;

  getAllItems(): CartItem[] {
    return this.database.getAllItems();
  }
}

```

With this setup, we are ready for the next step (and the best reason to use Dependency Injection)

##### Writing clean tests

All that is left now is to define a mock to be injected instead of the previously defined DataSource. Let's just do this - again by using @injectable:

```
const MOCK_ITEMS = [
  {
    id: "1",
    productId: "Item 1",
    quantity: 1,
  },
  {
    id: "2",
    productId: "Item 2",
    quantity: 2,
  },
];

@injectable()
class MockDataSource implements IDataSource {
  getAllItems(): CartItem[] {
    return MOCK_ITEMS;
  }
}
```

Now we are ready to write clean test cases:

```
describe("MongoDBService", () => {
  
  let dbService: MongoDBService;
  
  beforeEach(() => {
    container
    .registerInstance(DataSource, new MockDataSource());
    dbService = container.resolve(MongoDBService);
  });

  test("should be defined", () => {
    expect(dbService).toBeDefined();
  });

  test("should return all items", () => {
    expect(dbService.getAllItems()).toEqual(MOCK_ITEMS);
  });
});
```

In the Jest lifecycle method beforeEach, we register the MockDataSource for the DataSource. So TSyringe now resolves the DataSource to MockDataSource instead of the "real" DataSource - that might actually change items, alter tables, or might have other side effects.

##### Wrap up

A lightweight yet scalable stack for microservices is a crucial factor to keep services manageable. With the proposed setup, you might meet these requirements - but still: Beware of microservices that might grow into monoliths over time ;)
