nest-dapr package

Develop NestJS microservices using Dapr pubsub and bindings.

What is Dapr?

The Distributed Application Runtime Dapr provides APIs that simplify microservice connectivity. Whether your communication pattern is service to service invocation or pub/sub messaging, Dapr helps you write resilient and secured microservices.

What is nest-dapr package?

nest-dapr is a NestJS module which provides a set of decorators and services to integrate with DaprJS SDK.

Getting started

Install nest-dapr package into your Nest project.

npm i --save @dbc-tech/nest-dapr

Import DaprModule into your AppModule

@Module({
  imports: [DaprModule.register()],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Import DaprClient from @dapr/dapr package and add dependency to AppController

import { DaprClient } from '@dapr/dapr'
import { Controller, Get } from '@nestjs/common'
import { AppService } from './app.service'

@Controller()
export class AppController {
  constructor(private readonly daprClient: DaprClient) {}
}

Create a pubsub handler

@DaprPubSub('rmq-pubsub', 'rmq-topic')
pubSubHandler(message: Message): void {
  console.log(`Received topic message:`, message);
}

In this example rmq-pubsub is the name of the Dapr pubsub component and rmq-topic is the name of the topic to subscribe to. Here's an example Dapr component.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: rmq-pubsub
  namespace: default
spec:
  type: pubsub.rabbitmq
  version: v1
  metadata:
    - name: host
      value: amqp://guest:guest@localhost:5674

Messages published to the rmq-topic topic will be received by the pubSubHandler method.

Create a binding handler

@DaprBinding('rmq-binding')
bindingHandler(message: Message): void {
  coneole.log('Received message:', message);
}

In this example rmq-binding is the name of the Dapr binding component. Here's an example Dapr component.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: rmq-binding
  namespace: default
spec:
  type: bindings.rabbitmq
  version: v1
  metadata:
    - name: queueName
      value: rmq-queue
    - name: host
      value: amqp://guest:guest@localhost:5674
    - name: durable
      value: true
    - name: deleteWhenUnused
      value: false
    - name: ttlInSeconds
      value: 60
    - name: prefetchCount
      value: 0
    - name: exclusive
      value: false
    - name: maxPriority
      value: 5
    - name: contentType
      value: 'text/plain'

Messages published to the rmq-queue queue as defined in the component will be received by the bindingHandler method.

For further information see the nest-dapr readme and documentation.