Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.
/ node-nats Public archive

Classes, functions and tools that help to connect and communicate to and with a NATS streaming server.

License

Notifications You must be signed in to change notification settings

egomobile/node-nats

Repository files navigation

npm last build PRs Welcome

@egomobile/nats

Classes, functions and tools that help to connect and communicate to and with a NATS streaming server, written in TypeScript.

Install

Execute the following command from your project folder, where your package.json file is stored:

npm install --save @egomobile/nats

Usage

import {
  INatsMessageConsumerContext,
  NatsClient,
  NatsMessageError
} from "@egomobile/nats"

interface IFooMessage {
  bar: number;
}

// creates and opens an instance to a NATS
// server using `NATS_URL`, `NATS_USER` and `NATS_PASSWORD`
// environment variables by default
const client = NatsClient.open({
  "name": process.env.POD_NAME!.trim()
})

// optional:
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController
const ac = new AbortController()

const consumer = client.createConsumer<IFooMessage>({ "streamName": "foo-stream" })
consumer.on("message", (context: INatsMessageConsumerContext<IFooMessage>) => {
  const {
    ack,
    message
  } = context

  // process `message` ...

  // ack() is usually executed automatically
})
consumer.on("error", (error: any) => {
  if (error instanceof NatsMessageError) {
    // is happends if handling a message failed
    //
    // error.msg contains `JsMsg`
    // error.cause contains inner exception
    console.error('Consumer message error:', error)
  } else {
    console.error('Consumer error:', error)
  }
})

const disposeSubscription = consumer.subscribe({
  signal: ac.signal
})

const publisher = client.createPublisher<IFooMessage>({ "streamName": "foo-stream" })
await publisher.publish({
  "bar": 42
})

setTimeout(() => {
  ac.abort()

  // alternative, if there is no AbortController:
  //
  // disposeSubscription()
}, 10000)

Documentation

The API documentation can be found here.