• Stars
    star
    112
  • Rank 312,240 (Top 7 %)
  • Language
    TypeScript
  • Created almost 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Example code for nestjs microservice using REDIS

nestjs-microservice-example

Example code for nestjs microservice using REDIS

Looking for Microservices using gRPC? (New 2022 solution using microservices written in nest.js and asp.net core using gRPC. Also has gateway api written in nest.js) *** https://github.com/itsmebhavin/nestjs-microservices-gRPC-example

Description

We are creating microservices using nestjs [nestjs.com] and REDIS. We have following components in our solution -

  • books-service (microservice)
  • magazines-service (microservice)
  • http-api (main entry point API for aggregating microservices)

How microservices are designed?

Books-Service (Microservice)


It's basically a CRUD API for managing books. We have books object as below -

export class CreateBookDTO {
  readonly id: number;
  readonly title: string;
  readonly description: string;
  readonly author: string;
}

Registering Books-Service with REDIS

main.ts \\ Bootstraping

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { BooksModule } from './books/books.module';
import { Transport } from '@nestjs/microservices';

// Create new logger instance
const logger = new Logger('Main');

// Create micro service options
const microserviceOptions = {
  name: 'BOOK_SERVICE',
  transport: Transport.REDIS,
  options: {
    host: 'localhost',
    port: 6379,
  },
};
async function bootstrap() {
  const app = await NestFactory.createMicroservice(
    AppModule,
    microserviceOptions,
  );
  app.listen(() => {
    logger.log('Books microservice is listening ... ');
  });
}
bootstrap();

Controller methods for microservice

To add method which you want to expose as endpoint, you have to add @MessagePattern({ cmd: <endpoint-name>}) attribute.

 @MessagePattern({ cmd: 'getBooks' })
  async getBooks() {
    const books = await this.booksService.getBooks();
    return books;
  }

Registering Magazines-Service with REDIS

This is similar to books microservice registration / bootstraping. We have same types of CRUD endpoints in magazines controller.


Note: We are serving data from the mocks file. Mocks files are in respective microservice code. e.g. books.mocks.ts and magazines.mocks.ts.


How aggregator Client API is designed?

Our aggrator API is nothing but simple nestjs API application, so there is no changes in main.ts bootstrapping. But main change will be in controllers where we are going to call individual microservices.

Client API is going to communicate with Microservice using REDIS messaging channel.

REDIS setup

  • I have REDIS running in docker in my windows machine.
  • After that, I have installed Redis-cli for windows (x64).
  • I verified that Redis is working by running $#> redis-cli on command prompt.

Now that my REDIS is running, I can use it in aggregator api as Transport channel.

books.controller.ts

  client: ClientProxy;
  logger = new Logger('Books');
  constructor() {
    this.client = ClientProxyFactory.create({
      transport: Transport.REDIS,
      options: {
        host: 'localhost',
        port: 6379,
      },
    });
  }

How to use ClientProxy?

@Get()
  async getBooks() {
    this.logger.log('Getting all books');
    const pattern = { cmd: 'getBooks' };
    return await this.client.send(pattern, {});
  }

How to run whole eco-system?

  • Need to run books-microservice using npm run start:dev
  • Need to run magazines-microservice using npm run start:dev

finally, after you have both microservices are running, let's start our aggregator api, so we can use it to build our client UI application.

  • Need to run http-api using npm run start:dev

Testing?

  • I got my aggregator api running on localhost:3000 and so i am using it in postman to test it.

Testing endpoints for books but same for magazines as well.

  1. GET localhost:3000\books
  2. GET localhost:3000\books\2
  3. POST localhost:3000\books
  {
    id: 8,
    title: 'Champak',
    description: 'Kids book for pre-k',
    author: 'John Barry',
  }

  • Author: Bhavin Patel
  • Todo: Work in progress to add Docker and kubernetes support.

More Repositories

1

Learning-Angular-2.0

Learning Angular 2.0 from Angular 2 Tutorial (2016) Mindspace Video Series(https://www.youtube.com/playlist?list=PL55RiY5tL51olfU2IEqr455EYLkrhmh3n)
TypeScript
35
star
2

nestjs-microservices-gRPC-example

gRPC Microservices example using nest.js and asp.net core microservices and nest.js based gateway API to consume in client app.
TypeScript
33
star
3

node-html-pdf-sample

Sample application for print pdf from node.js using middleware called 'node-html-pdf' and send it to angular.js client application.
HTML
16
star
4

bp-ngContextMenu

Angular Context Menu - for Mouse Click & Right button Click events.
HTML
12
star
5

nodejs-express-typescript-boilerplate

Sample boilerplate project for node.js, express using TypeScript and Gulp.
TypeScript
10
star
6

Electron-Angular4-Pouchdb

Electron and Angular 4 based desktop application using PouchDB & CouchDB
CSS
9
star
7

zxing-barcode-scanner-bigger-viewfinder

ngcordova / cordova plugin for Barcode scanner from ZXING project. This one will have bigger viewfinder to scan big barcodes like CODE-39
Java
8
star
8

angular-cli-pouchdb-couchdb

Angular 6 Cli based project for PouchDB and CouchDB setup
TypeScript
7
star
9

nodejs-express-es6-boilerplate

Sample boilerplate project for node.js and express using ES6 & Babel.
JavaScript
4
star
10

itsmebhavin.github.io

Web tech news articles (https://itsmebhavin.github.io)
HTML
3
star
11

zorin-os-xrdp

xrdp script for Enhanced Session under hyper-v
Shell
2
star
12

Elmah.Log4Net

This appender will allow log4net to be configured to send log messages to ELMAH directly. This way ELMAH can be the log manager of record for sites while still allowing specific logging parameters to be controlled with log4net as usual.
C#
1
star
13

nodewebkit-demo

nw.js also known as nodewebkit - Sample application using Angular.js
CSS
1
star
14

ionic-themeroller-sample

ionic4 based sample app in angular6 - Theme Roller task
TypeScript
1
star
15

ngBootstrapDateTimePicker

Angular directives for Twitter Bootstrap 3 - DateTime Picker.
JavaScript
1
star
16

nodejs-express-tutorial

Tutorial series for node.js from basic setup to express code using mongodb and implementing loggers, unit testing, clustering, Auth., router etc.
JavaScript
1
star