Classes, functions and tools that help to connect and communicate to and with a NATS streaming server, written in TypeScript.
Execute the following command from your project folder, where your package.json
file is stored:
npm install --save @egomobile/nats
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)
The API documentation can be found here.