@cloudamqp/amqp-client
Version:
AMQP 0-9-1 client, both for browsers (WebSocket) and node (TCP Socket)
101 lines • 3.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AMQPGeneratorSubscription = exports.AMQPSubscription = void 0;
const amqp_consumer_js_1 = require("./amqp-consumer.js");
const amqp_codec_registry_js_1 = require("./amqp-codec-registry.js");
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;
}
}
exports.AMQPSubscription = AMQPSubscription;
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 amqp_consumer_js_1.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 (0, amqp_codec_registry_js_1.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;
});
}
}
}
}
exports.AMQPGeneratorSubscription = AMQPGeneratorSubscription;
//# sourceMappingURL=amqp-subscription.js.map