import { Inject, Injectable, Logger, OnModuleDestroy, } from '@nestjs/common'; import { StringCodec } from 'nats'; import type { Msg, NatsConnection, Subscription } from 'nats'; import { NATS_CLIENT } from './nats.constants'; export type NatsMessageHandler = ( data: T, msg: Msg, ) => Promise | void; @Injectable() export class NatsService implements OnModuleDestroy { private readonly logger = new Logger(NatsService.name); private readonly stringCodec = StringCodec(); private readonly subscriptions = new Set(); constructor( @Inject(NATS_CLIENT) private readonly natsClient: NatsConnection, ) {} async onModuleDestroy() { for (const sub of this.subscriptions) { try { sub.unsubscribe(); } catch { // ignore } } this.subscriptions.clear(); try { const closed = this.natsClient.closed(); await this.natsClient.drain(); const err = await closed; if (err) this.logger.error(`NATS closed with error: ${err}`); } catch { try { await this.natsClient.close(); } catch { // ignore } } } public async publish(subject: string, data: T): Promise { this.natsClient.publish( subject, this.stringCodec.encode(JSON.stringify(data)), ); await this.natsClient.flush(); } public subscribe( subject: string, handler: NatsMessageHandler, options?: { queue?: string }, ): Subscription { const sub = this.natsClient.subscribe(subject, { queue: options?.queue, }); this.subscriptions.add(sub); void this.consumeSubscription(sub, handler); return sub; } private async consumeSubscription( sub: Subscription, handler: NatsMessageHandler, ): Promise { try { for await (const msg of sub) { await this.dispatch(msg, handler); } } catch (err) { this.logger.error( `NATS subscription on subject="${sub.getSubject()}" terminated: ${ (err as Error)?.message ?? err }`, ); } finally { this.subscriptions.delete(sub); } } private async dispatch( msg: Msg, handler: NatsMessageHandler, ): Promise { let data: T; try { const decoded = this.stringCodec.decode(msg.data); data = JSON.parse(decoded) as T; } catch (err) { this.logger.warn( `Failed to decode NATS message on subject="${msg.subject}": ${ (err as Error)?.message ?? err }`, ); return; } try { await handler(data, msg); } catch (err) { this.logger.error( `Handler error on subject="${msg.subject}": ${ (err as Error)?.stack ?? err }`, ); } } }