Skip to content

Nats

Re-exporting the most used types and functions from the nats.ws package.

Example

import { Msg, JSONCodec, ... } from '@wuespace/telestion/nats';

See

  • https://docs.nats.io/using-nats/developer
  • https://github.com/nats-io/nats.ws#readme

Classes

NatsError

Extends

Constructors

new NatsError()
new NatsError(
   message, 
   code, 
   chainedError?): NatsError
Parameters
message

string

code

string

chainedError?

Error

Returns

NatsError

Api

private

Overrides

Error.constructor

Properties

api_error?
optional api_error: ApiError;

chainedError?
optional chainedError: Error;

code
code: string;

message
message: string;
Overrides

Error.message

name
name: string;
Overrides

Error.name

permissionContext?
optional permissionContext: object;

operation
operation: string;

queue?
optional queue: string;

subject
subject: string;

stack?
optional stack: string;
Inherited from

Error.stack

prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;

Optional override for formatting stack traces

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace

stackTraceLimit
static stackTraceLimit: number;
Inherited from

Error.stackTraceLimit

Methods

isAuthError()
isAuthError(): boolean
Returns

boolean

isAuthTimeout()
isAuthTimeout(): boolean
Returns

boolean

isJetStreamError()
isJetStreamError(): boolean
Returns

boolean

isPermissionError()
isPermissionError(): boolean
Returns

boolean

isProtocolError()
isProtocolError(): boolean
Returns

boolean

jsError()
jsError(): null | ApiError
Returns

null | ApiError

captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace

errorForCode()
static errorForCode(code, chainedError?): NatsError
Parameters
code

string

chainedError?

Error

Returns

NatsError

Interfaces

Codec<T>

Type Parameters

T

Methods

decode()
decode(a): T

Decode an Uint8Array from a message payload into a T

Parameters
a

Uint8Array<ArrayBufferLike>

Returns

T

encode()
encode(d): Uint8Array<ArrayBufferLike>

Encode T to an Uint8Array suitable for including in a message payload.

Parameters
d

T

Returns

Uint8Array<ArrayBufferLike>


Msg

Represents a message delivered by NATS. This interface is used by Subscribers.

Properties

data
data: Uint8Array<ArrayBufferLike>;

The message’s data (or payload)

headers?
optional headers: MsgHdrs;

Possible headers that may have been set by the server or the publisher.

reply?
optional reply: string;

A possible subject where the recipient may publish a reply (in the cases where the message represents a request).

sid
sid: number;

The subscription ID where the message was dispatched.

subject
subject: string;

The subject the message was sent to

Methods

json()
json<T>(reviver?): T

Convenience method to parse the message payload as JSON. This method will throw an exception if there’s a parsing error;

Type Parameters

T

Parameters
reviver?

ReviverFn

a reviver function

Returns

T

respond()
respond(payload?, opts?): boolean

Convenience to publish a response to the reply subject in the message - this is the same as doing nc.publish(msg.reply, ...).

Parameters
payload?

Payload

opts?

PublishOptions

Returns

boolean

string()
string(): string

Convenience method to parse the message payload as string. This method may throw an exception if there’s a conversion error

Returns

string


MsgHdrs

Extends

Properties

code
code: number;

description
description: string;

hasError
hasError: boolean;

status
status: string;

Methods

[iterator]()
iterator: Iterator<[string, string[]], any, any>
Returns

Iterator<[string, string[]], any, any>

Inherited from

Iterable.[iterator]

append()
append(
   k, 
   v, 
   match?): void
Parameters
k

string

v

string

match?

Match

Returns

void

delete()
delete(k, match?): void
Parameters
k

string

match?

Match

Returns

void

get()
get(k, match?): string
Parameters
k

string

match?

Match

Returns

string

has()
has(k, match?): boolean
Parameters
k

string

match?

Match

Returns

boolean

keys()
keys(): string[]
Returns

string[]

last()
last(k, match?): string
Parameters
k

string

match?

Match

Returns

string

set()
set(
   k, 
   v, 
   match?): void
Parameters
k

string

v

string

match?

Match

Returns

void

values()
values(k, match?): string[]
Parameters
k

string

match?

Match

Returns

string[]


NatsConnection

Properties

info?
optional info: ServerInfo;

ServerInfo to the currently connected server or undefined

services
services: ServicesAPI;

Returns a ServicesAPI which allows you to build services using NATS.

Methods

close()
close(): Promise<void>

Close will close the connection to the server. This call will terminate all pending requests and subscriptions. The returned promise resolves when the connection closes.

Returns

Promise<void>

closed()
closed(): Promise<void | Error>

Returns a promise that can be used to monitor if the client closes. The promise can resolve an Error if the reason for the close was an error. Note that the promise doesn’t reject, but rather resolves to the error if there was one.

Returns

Promise<void | Error>

drain()
drain(): Promise<void>

Initiates a drain on the connection and returns a promise that resolves when the drain completes and the connection closes.

Drain is an ordered shutdown of the client. Instead of abruptly closing the client, subscriptions are drained, that is messages not yet processed by a subscription are handled before the subscription is closed. After subscriptions are drained it is not possible to create a new subscription. Then all pending outbound messages are sent to the server. Finally, the connection is closed.

Returns

Promise<void>

flush()
flush(): Promise<void>

Returns a Promise that resolves when the client receives a reply from the server. Use of this API is not necessary by clients.

Returns

Promise<void>

getServer()
getServer(): string

Returns the hostport of the server the client is connected to.

Returns

string

isClosed()
isClosed(): boolean

Returns true if the client is closed.

Returns

boolean

isDraining()
isDraining(): boolean

Returns true if the client is draining.

Returns

boolean

jetstream()
jetstream(opts?): JetStreamClient

Returns a JetStreamClient which allows publishing messages to JetStream or consuming messages from streams.

Parameters
opts?

JetStreamManagerOptions | JetStreamOptions

Returns

JetStreamClient

jetstreamManager()
jetstreamManager(opts?): Promise<JetStreamManager>

Returns a Promise to a JetStreamManager which allows the client to access Streams and Consumers information.

Parameters
opts?

JetStreamManagerOptions

Returns

Promise<JetStreamManager>

publish()
publish(
   subject, 
   payload?, 
   options?): void

Publishes the specified data to the specified subject.

Parameters
subject

string

payload?

Payload

options?

PublishOptions

Returns

void

publishMessage()
publishMessage(msg): void

Publishes using the subject of the specified message, specifying the data, headers and reply found in the message if any.

Parameters
msg

Msg

Returns

void

reconnect()
reconnect(): Promise<void>

Use of this API is experimental, and it is subject to be removed.

reconnect() enables a client to force a reconnect. A reconnect will disconnect the client, and possibly initiate a reconnect to the cluster. Note that all reconnect caveats apply:

  • If the reconnection policy given to the client doesn’t allow reconnects, the connection will close.

  • Messages that are inbound or outbound could be lost.

  • All requests that are in flight will be rejected.

Note that the returned promise will reject if the client is already closed, or if it is in the process of draining. If the client is currently disconnected, this API has no effect, as the client is already attempting to reconnect.

Returns

Promise<void>

request()
request(
   subject, 
   payload?, 
opts?): Promise<Msg>

Publishes a request with specified data in the specified subject expecting a response before RequestOptions#timeout milliseconds. The api returns a Promise that resolves when the first response to the request is received. If there are no responders (a subscription) listening on the request subject, the request will fail as soon as the server processes it.

Parameters
subject

string

payload?

Payload

opts?

RequestOptions

Returns

Promise<Msg>

requestMany()
requestMany(
   subject, 
   payload?, 
opts?): Promise<AsyncIterable<Msg, any, any>>

Publishes a request expecting multiple responses back. Several strategies to determine when the request should stop gathering responses.

Parameters
subject

string

payload?

Payload

opts?

Partial<RequestManyOptions>

Returns

Promise<AsyncIterable<Msg, any, any>>

respondMessage()
respondMessage(msg): boolean

Replies using the reply subject of the specified message, specifying the data, headers in the message if any.

Parameters
msg

Msg

Returns

boolean

rtt()
rtt(): Promise<number>
Returns

Promise<number>

the number of milliseconds it took for a flush.

stats()
stats(): Stats

Returns some metrics such as the number of messages and bytes sent and recieved by the client.

Returns

Stats

status()
status(): AsyncIterable<Status, any, any>

Returns an async iterator of Status that may be useful in understanding when the client looses a connection, or reconnects, or receives an update from the cluster among other things.

Returns

AsyncIterable<Status, any, any>

an AsyncIterable

subscribe()
subscribe(subject, opts?): Subscription

Subscribe expresses interest in the specified subject. The subject may have wildcards. Messages are delivered to the SubscriptionOptions callback if specified. Otherwise, the subscription is an async iterator for Msg.

Parameters
subject

string

opts?

SubscriptionOptions

Returns

Subscription


PublishOptions

Properties

headers?
optional headers: MsgHdrs;

Optional headers to include with the message.

reply?
optional reply: string;

An optional subject where a response should be sent. Note you must have a subscription listening on this subject to receive the response.


RequestOptions

Properties

headers?
optional headers: MsgHdrs;

MsgHdrs to include with the request.

noMux?
optional noMux: boolean;

If true, the request API will create a regular NATS subscription to process the response. Otherwise a shared muxed subscriptions is used. Requires reply

reply?
optional reply: string;

The subject where the response should be sent to. Requires noMux

timeout
timeout: number;

number of milliseconds before the request will timeout.


Sub<T>

Basic interface to a Subscription type

Extends

  • AsyncIterable<T>

Type Parameters

T

Properties

closed
closed: Promise<void>;

A promise that resolves when the subscription closes

Methods

[asyncIterator]()
asyncIterator: AsyncIterator<T, any, any>
Returns

AsyncIterator<T, any, any>

Inherited from

AsyncIterable.[asyncIterator]

drain()
drain(): Promise<void>

Drain the subscription, closing it after processing all messages currently in flight for the client. Returns a promise that resolves when the subscription finished draining.

Returns

Promise<void>

getMax()
getMax(): undefined | number

Return the max number of messages before the subscription will unsubscribe.

Returns

undefined | number

getPending()
getPending(): number

Returns the number of messages that are pending processing. Note that this is method is only valid for iterators.

Returns

number

getProcessed()
getProcessed(): number

Returns the number of messages that have been processed by the subscription.

Returns

number

getReceived()
getReceived(): number

Returns the number of messages received by the subscription.

Returns

number

getSubject()
getSubject(): string

Returns the subject that was used to create the subscription.

Returns

string

isClosed()
isClosed(): boolean

Returns true if the subscription is closed.

Returns

boolean

isDraining()
isDraining(): boolean

Returns true if the subscription is draining.

Returns

boolean

unsubscribe()
unsubscribe(max?): void

Stop the subscription from receiving messages. You can optionally specify that the subscription should stop after the specified number of messages have been received. Note this count is since the lifetime of the subscription.

Parameters
max?

number

Returns

void


SubOpts<T>

Subscription Options

Type Parameters

T

Properties

callback()?
optional callback: (err, msg) => void;

An optional function that will handle messages. Typically, messages are processed via an async iterator on the subscription. If this option is provided, messages are processed by the specified function.

Parameters
err

null | NatsError

msg

T

Returns

void

max?
optional max: number;

Optional maximum number of messages to deliver to the subscription before it is auto-unsubscribed.

queue?
optional queue: string;

Optional queue name (subscriptions on the same subject that use queues are horizontally load balanced when part of the same queue).

timeout?
optional timeout: number;

Optional maximum number of milliseconds before a timer raises an error. This useful to monitor a subscription that is expected to yield messages. The timer is cancelled when the first message is received by the subscription.

Type Aliases

MsgRequest

type MsgRequest: SeqMsgRequest | LastForMsgRequest | number;

Subscription

type Subscription: Sub<Msg>;

Type alias for NATS core subscriptions


SubscriptionOptions

type SubscriptionOptions: SubOpts<Msg>;

Subscription Options

Functions

headers()

function headers(code?, description?): MsgHdrs

Parameters

code?

number

description?

string

Returns

MsgHdrs


StringCodec()

function StringCodec(): Codec<string>

Returns a Codec for encoding strings to a message payload and decoding message payloads into strings.

Returns

Codec<string>

References

JSONCodec

Re-exports JSONCodec