📘
@node-test/bus
  • @node-ts/bus
  • Getting started
    • Installation
    • Handling messages
    • Shutting down cleanly
  • Reference
    • Bus
    • BusConfiguration
    • BusInstance
  • Getting help
  • Guide
    • Messages
      • Events
      • Commands
      • System messages
    • Message attributes
      • Correlation id
      • Attributes
      • Sticky attributes
    • Workflows
      • Creating a workflow
      • Starting
      • Handling
      • State
      • Completing
      • Example
    • Transports
      • RabbitMQ
      • Amazon SQS
      • Redis
      • Custom transports
    • Persistence
      • Postgres
      • MongoDB
      • Creating a persistence
    • Serializers
      • Class serializer
    • Loggers
      • Custom loggers
    • Middleware
    • Lifecycle hooks
    • Retry Strategies
    • Dependency injection
    • Long running processes
Powered by GitBook
On this page

Was this helpful?

  1. Getting started

Handling messages

PreviousInstallationNextShutting down cleanly

Last updated 3 years ago

Was this helpful?

At some point you'll want to handle messages that have been sent to your application. This can be done by creating a handler and registering it with the .

The following example creates a handler for a hotel booking application

Declare a command that models the ReserveRoom command

// reserve-room.ts

import { Command } from '@node-ts/bus-messages'

export class ReserveRoom extends Command {
  $name = 'reservations/reserve-room'
  $version = 0
  
  constructor (
    readonly roomId: string,
    readonly bookingId: string
  ) {
    super()
  }
}

Create a handler that receives a command to ReserveRoom that it delegates the operation to a reservationService.

Handlers should be kept as dumb as possible and delegate the work to dedicated services. This will help keep the messaging concerns of your application decoupled from the actual work it needs to do.

// reserve-room-handler.ts

import { handlerFor } from '@node-ts/bus-core'
import { ReserveRoom } from '../messages'
import { reservationService } from '../services'

export const reserveRoomHandler = handlerFor(
  ReserveRoom,
  command => reservationService.reserveRoom(command.reservation, command.bookingId)
)

Register the handler with the BusConfiguration.

// application.ts

import { Bus, BusInstance } from '@node-ts/bus-core'
import { reserveRoomHandler } from './handlers'
import { ReserveRoom } from './messages'

let bus: BusInstance
const start = async () => {
  bus = await Bus.configure()
    .withHandler(reserveRoomHandler)
    .initialize()
    
  // Start the bus to commence processing messages
  await bus.start()
}

start
  .then(async () => bus.send(new ReserveRoom(
    '63a65cf0-d239-4b83-96da-f33f013db23a',
    '12b85a56-e929-47a8-9ac3-e87739d5d215'
  ))
  .catch(console.error)
BusConfiguration