Git Product home page Git Product logo

nestjs-nats-jetstream-transporter's Introduction

NestJS NATS JetStream Transporter

A NATS transporter for NestJS that takes advantage of JetStream for event patterns.

Installation

$ npm install @samkrew/nestjs-nats-jetstream-transporter nats@latest

Publishing Messages

The NatsClient works mostly the same with the built-in NATS transporter for NestJS. The only difference is that you must instantiate NatsClient yourself.

Request-Reply

// main.ts
import { NatsTransportStrategy } from "nestjs-nats-jetstream-transporter";

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy()
});

await app.listenAsync();
// math.controller.ts
import { NatsClient } from "nestjs-nats-jetstream-transporter";

@Controller()
export class MathController {
  private readonly client = new NatsClient();

  accumulate(): Observable<number> {
    return this.client.send<number>("sum", [1, 2, 3]);
  }
}

Event-Based

// main.ts
import { NatsTransportStrategy } from "nestjs-nats-jetstream-transporter";

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy({
    // Create a stream with a subject called "orders.created"
    // This is important later on when we publish an event with NatsClient
    streams: [
      {
        name: "orders-events",
        subjects: ["orders.created"]
      }
    ]
  })
});

await app.listenAsync();
// orders.controller.ts
import { NatsClient } from "nestjs-nats-jetstream-transporter";

@Controller()
export class OrdersController {
  private readonly client = new NatsClient();

  constructor(private readonly ordersService: OrdersService) {}

  async create(): Promise<void> {
    const order = await this.ordersService.create();

    this.client.emit("orders.created", order);
  }
}

Receiving Messages

There are no special changes needed to receive messages. Just use the @EventPattern() and @MessagePattern() decorators provided by NestJS.

@Ctx() works exactly the same, however you should use the NatsContext provided by this package as the parameter type. It exposes an additional getMessage() method that returns the original message object if needed.

Customizing JetStream consumer options

You can customize how the JetStream push consumer behaves. One example is making the consumer durable to survive application restarts. Another example is taking advantage of distributed queues for horozontal scaling.

Read more about JetStream consumers here, and refer to the underlying API here.

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy({
    consumer: (options) => {
      options.durable("my-durable-name");
      options.queue("my-queue-group");
    }
  })
});

NACK and TERM JetStream messages

By default, all JetStream messages are automatically acknowledged. However, you can also NACK and TERM the message by returning the respective symbols from your application.

Returning NACK will ask for the message to be redelivered, while TERM will terminate future deliveries of the message.

// shipping.controller.ts
import { NACK, TERM } from "nestjs-nats-jetstream-transporter";

@Controller()
export class ShippingController {
  constructor(private readonly shippingService: ShippingService) {}

  @EventPattern("orders.created")
  handleCreatedOrder(order) {
    // If a shipment cannot be scheduled at this time, then ask for the message to be redelivered
    if (this.shippingService.isBusy()) {
      return NACK;
    }

    // If a shipment already exists for this order, then terminate the redelivery of this message
    if (this.shippingService.exists(order)) {
      return TERM;
    }

    this.shippingService.scheduleShipment(order);
    
    // Otherwise, the message will be auto-acked
  }
}

If the handler for your event pattern throws an error, the message will automatically be terminated. You can change this behavior by providing an onError function to the transport strategy options.

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy({
    // Messages that caused an exception will be acked instead
    onError: (message) => message.ack()
  })
});

Queue Groups

You can specify a queue group name to enable distributed queues. This will load balance message delivery across all other application instances with the same queue group name. It makes horozontal scaling simple as you can scale up by running another instance of your application with no additional configuration.

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy({
    queue: "my-queue-group"
  })
});

If you want to enable this functionality for event patterns, you must also specify the queue group name using the JetStream consumer options builder.

const app = await NestFactory.createMicroservice(AppModule, {
  strategy: new NatsTransportStrategy({
    consumer: (options) => options.queue("my-queue-group"),
    queue: "my-queue-group"
  })
});

Tests

$ npm run test

Disclaimer

This repository forked from @alexy4744/nestjs-nats-jetstream-transporter

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.