Implementing Microservices with NodeJS TypeScript using the Moleculer Framework
Introduction
Implementing in an Existing NodeJS Project
To create a service like this:
The result when the service starts successfully
Creating a Boilerplate with a CLI Tool
First, you need to install the CLI tool.
Next, let's create a template codebase for NodeJS with TypeScript.
Once the setup is complete, the codebase will include all necessary resources such as:
- Folder mixins: A flexible way to distribute reusable functionalities for Moleculer services.
- Folder services: Pre-defined default services.
- Folder test: Uses Jest for testing.
- File moleculer.config.ts: For configuration purposes.
- DockerFile: To build the Docker image, and docker compose to start with Docker.
- k8s.yml: To start with Kubernetes.
- Prettier: To format code.
- ESLint: To check syntax according to the rules defined during development.
To start the project:
When you access the homepage, you'll find information about the components of Microservices, Rest API, Nodes, and Services.
Restful API document
Codebase Explanation
APIService
In the `services/api.service.ts` file, some default configuration info is defined, which you can change as needed, such as:
You can see that the default port used is 3000, and the prefix to access the Restful API is `/api`.
GreeterService
Let's take a look at a simple service defined in `services/greeter.service.ts`.
You can see that the two actions defined are equivalent to two services. They clearly define the GET method, path, and parameters. There are two ways to use these actions:
1. Use them directly through the NodeJS REPL after starting the microservices
2. Calling via Restful API
ProductService
Next, let's move on to a more complex service: `services/product.service.ts`.First, let's take a look at the Mixins and Methods being used.
The methods defined will be used in ProductService or in Mixins. In this case, the `seedDB` method is used to create default data after establishing a database connection and if the collection is empty. This implementation is defined in `mixins/db.mixin.ts` with the `started` function.
Next, let's connect to the database defined by the environment variables:
- If `MONGO_URI` is defined, we will use MongoDB.
- If `NODE_ENV` is set to `test`, data will be stored in memory.
- By default, data will be saved to the file `data/products.db`, with the product name provided when calling the `DbMixin("products")` mixin.
Next up are the actions. Since we're using Mixin with `moleculer-db`, it automatically injects default actions like list, find, count, create, insert, update, and remove into the ProductService action for interacting with the Product entity. Additionally, we define two more actions to increase or decrease the product quantity.
Comments
Post a Comment