UNPKG

@cloudamqp/amqp-client

Version:

AMQP 0-9-1 client, both for browsers (WebSocket) and node (TCP Socket)

96 lines 2.92 kB
import { AMQPGeneratorConsumer } from "./amqp-consumer.js"; import { decodeMessage } from "./amqp-codec-registry.js"; export class AMQPSubscription { constructor(consumer, def) { this.consumer = consumer; this.def = def; } get channel() { return this.consumer.channel; } get consumerTag() { return this.consumer.tag; } async cancel() { this.onCancel?.(); const ch = this.consumer.channel; try { await this.consumer.cancel(); } catch { } if (!ch.closed) { try { await ch.close(); } catch { } } } setConsumer(consumer) { this.consumer = consumer; } } export class AMQPGeneratorSubscription extends AMQPSubscription { constructor() { super(...arguments); this.stopped = false; } setConsumer(consumer) { super.setConsumer(consumer); this.consumerReady?.(); delete this.consumerReady; } async cancel() { this.stopped = true; this.consumerReady?.(); delete this.consumerReady; await super.cancel(); } async *[Symbol.asyncIterator]() { const autoAck = !this.def.consumeParams.noAck; const requeueOnNack = this.def.requeueOnNack ?? true; let prev; while (!this.stopped) { const consumer = this.consumer; if (!(consumer instanceof AMQPGeneratorConsumer)) { throw new Error("Cannot iterate messages on a callback-based subscription"); } let decodeError; try { for await (const msg of consumer.messages) { if (this.stopped) return; if (autoAck) await prev?.ack(); if (this.def.parsers || this.def.coders) { try { await decodeMessage(msg, this.def.parsers ?? {}, this.def.coders ?? {}); } catch (err) { if (autoAck) { await msg.nack(requeueOnNack); continue; } decodeError = err; throw err; } } prev = msg; yield msg; } } catch (err) { if (err === decodeError) throw err; } prev = undefined; if (!this.stopped) { await new Promise((resolve) => { this.consumerReady = resolve; }); } } } } //# sourceMappingURL=amqp-subscription.js.map