@egomobile/nats
TypeScript icon, indicating that this package has built-in type declarations

0.5.0 • Public • Published

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.

Package Sidebar

Install

npm i @egomobile/nats

Weekly Downloads

0

Version

0.5.0

License

LGPL-3.0

Unpacked Size

51.7 kB

Total Files

20

Last publish

Collaborators

  • ekmobile
  • egodux
  • mkloubert
  • ekegodigital