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

Refactor/new nats lib #4

Merged
9 commits merged into from
Jan 9, 2024
Merged

Refactor/new nats lib #4

9 commits merged into from
Jan 9, 2024

Conversation

ghost
Copy link

@ghost ghost commented Jan 8, 2024

@zulfiqarjunejo @ekmobile

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>()
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>()
await publisher.publish({
  "bar": 42
})

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

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

Marcel Kloubert and others added 3 commits January 8, 2024 17:08
@ghost ghost requested a review from zulfiqarjunejo January 8, 2024 16:30
@ghost
Copy link
Author

ghost commented Jan 9, 2024

@zulfiqarjunejo @ekmobile

I refactored the consumer class a little bit, so it does the ack() in message callbacks automatically now

@ghost ghost merged commit bd2e966 into main Jan 9, 2024
1 check passed
This pull request was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant