UNPKG

smqp

Version:

Synchronous message queueing package

56 lines (55 loc) 1.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Message = Message; exports.kPending = void 0; var _shared = require("./shared.js"); const kPending = exports.kPending = Symbol.for('pending'); const kOnConsumed = Symbol.for('onConsumed'); function Message(fields, content, properties, onConsumed) { this[kOnConsumed] = [null, onConsumed]; this[kPending] = false; const mproperties = { ...properties, messageId: properties?.messageId || `smq.mid-${(0, _shared.generateId)()}` }; const timestamp = mproperties.timestamp = mproperties.timestamp || Date.now(); if (mproperties.expiration) { mproperties.ttl = timestamp + parseInt(mproperties.expiration); } const { consumerTag, ...mfields } = fields; this.fields = mfields; this.content = content; this.properties = mproperties; } Object.defineProperty(Message.prototype, 'pending', { get() { return this[kPending]; } }); Message.prototype.ack = function ack(allUpTo) { if (!this[kPending]) return; for (const fn of this[kOnConsumed]) { if (fn) fn(this, 'ack', allUpTo); } this[kPending] = false; }; Message.prototype.nack = function nack(allUpTo, requeue = true) { if (!this[kPending]) return; for (const fn of this[kOnConsumed]) { if (fn) fn(this, 'nack', allUpTo, requeue); } this[kPending] = false; }; Message.prototype.reject = function reject(requeue = true) { this.nack(false, requeue); }; Message.prototype._consume = function consume(consumerTag, consumedCb) { this[kPending] = true; this.fields.consumerTag = consumerTag; this[kOnConsumed][0] = consumedCb; };