Class: ConnectedClient
TypeScript 0.4.0 · Source commit cbff27b8a34e1384384018680e46c20d5c610cc9. Generated with reviewed comment corrections; see generation notes.
Defined in: connection.ts:119
Connection class for PostgreMQ client Manages the connection to PostgreSQL and provides methods for queue operations.
This page documents the inferred client returned by connect(). ConnectedClient is a documentation label, not a named export from postgremq. Use type inference or the exported option types in application code.
Implements
Methods
cleanupCompletedMessages()
cleanupCompletedMessages(
olderThanHours?):Promise<number>
Defined in: connection.ts:1498
Delete up to 1000 completed delivery rows beyond the retention window. Also remove eligible unreferenced payloads; these do not increase the return count. Call repeatedly to work through a larger backlog.
Parameters
olderThanHours?
number
Retention in nonnegative integer hours; default 24.
Returns
Promise<number>
Number of completed delivery rows deleted, not payload count.
Throws
A raw PostgreSQL error for rejected retention arguments; this method does not translate PMQ03 to ValidationError.
Implementation of
Connection.cleanupCompletedMessages
cleanUpQueue()
cleanUpQueue(
queue):Promise<void>
Defined in: connection.ts:1454
Remove every delivery row from the named queue: pending, processing, and completed. Preserve the queue, topic payloads, and dead letters.
Parameters
queue
string
The queue name
Returns
Promise<void>
Promise that resolves when the queue is cleaned up
Implementation of
cleanUpTopic()
cleanUpTopic(
topic):Promise<void>
Defined in: connection.ts:1469
Remove topic payloads and their deliveries across every subscribed queue; refuses topics with dead letters.
Parameters
topic
string
The topic name
Returns
Promise<void>
Promise that resolves when the topic is cleaned up
Implementation of
close()
close():
Promise<void>
Defined in: connection.ts:344
Close the connection and clean up resources
Returns
Promise<void>
Promise that resolves when disconnected
Implementation of
connect()
connect():
Promise<void>
Defined in: connection.ts:326
Connect to the database and check PostgreMQ schema compatibility
close() is terminal — once a connection has been closed, calling connect() again throws ConnectionClosedError rather than silently succeeding into a half-broken state (the pool may have been .end()'d, notification machinery torn down, etc.). Callers must construct a new Connection to reconnect.
It reads postgremq.info() and rejects a database whose schema version
has an mq major not in SUPPORTED_MQ_MAJORS, that reports no schema
version, or that has no discovery function (it needs a PostgreMQ
installation or upgrade).
Notification listening starts lazily on the first subscription. This check does not inspect migration dirty state; use CLI status before starting applications after an upgrade.
Returns
Promise<void>
Promise that resolves when connected
Throws
ConnectionClosedError if close() has already been called.
Throws
CompatibilityError if the installation is not compatible.
Implementation of
consume()
consume(
queue,options?):Consumer
Defined in: connection.ts:773
Create a consumer for a queue
Parameters
queue
string
The queue name
options?
Partial<ConsumerOptions> = {}
Consumer options
Returns
A new consumer instance
Implementation of
consumeHandler()
consumeHandler(
queue,handler,options?):HandlerConsumer
Defined in: connection.ts:809
Create a handler-based consumer for a queue.
Each message is dispatched to handler. The push-based counterpart to
consume()'s for await iteration, mirroring the Go client's
ConsumeHandler. Settlement rules:
- live handler returns without settlement -> message auto-acked
- handler throws or returns cancelled -> message auto-nacked
- handler settles the message itself -> no automatic action
options.maxInFlight bounds how many handlers run concurrently (0 =
unlimited, the default). Handlers receive a message whose signal
fires on shutdown / lease loss; long-running handlers should check it.
Parameters
queue
string
The queue name
handler
Per-message handler
options?
Partial<HandlerConsumerOptions> = {}
Consumer options plus maxInFlight
Returns
A started HandlerConsumer; call stop() to shut it down
Example
const hc = connection.consumeHandler('orders', async (msg) => {
await processOrder(msg.payload); // auto-acked on return
}, { topic: 'orders', maxInFlight: 10 });
// ... later ...
await hc.stop();
Implementation of
createQueue()
createQueue(
name,topic,exclusive?,options?):Promise<void>
Defined in: connection.ts:857
Create a new queue
Parameters
name
string
The queue name
topic
string
The topic name
exclusive?
boolean = false
Whether the queue is exclusive (temporary, kept alive by this connection)
options?
QueueOptions = {}
Queue options
Returns
Promise<void>
Promise that resolves when the queue is created
Implementation of
createTopic()
createTopic(
topic):Promise<void>
Defined in: connection.ts:835
Create a new topic
Parameters
topic
string
The topic name
Returns
Promise<void>
Promise that resolves when the topic is created
Implementation of
deleteInactiveQueues()
deleteInactiveQueues():
Promise<void>
Defined in: connection.ts:1483
Delete inactive (expired) exclusive queues
Returns
Promise<void>
Promise that resolves when inactive queues are deleted
Implementation of
Connection.deleteInactiveQueues
deleteQueue()
deleteQueue(
queue):Promise<void>
Defined in: connection.ts:938
Delete a queue
Parameters
queue
string
The queue name
Returns
Promise<void>
Promise that resolves when the queue is deleted
Implementation of
deleteQueueMessage()
deleteQueueMessage(
queue,messageID):Promise<void>
Defined in: connection.ts:1125
Delete a specific message from a queue
Parameters
queue
string
The queue name
messageID
number
The message ID
Returns
Promise<void>
Promise that resolves when the message is deleted
Implementation of
deleteTopic()
deleteTopic(
topic):Promise<void>
Defined in: connection.ts:919
Delete a topic
Parameters
topic
string
The topic name
Returns
Promise<void>
Promise that resolves when the topic is deleted
Implementation of
getMessage()
getMessage(
messageID):Promise<PublishedMessage|null>
Defined in: connection.ts:1167
Get a specific message by ID
Parameters
messageID
number
The message ID
Returns
Promise<PublishedMessage | null>
Promise that resolves to the message information or null if not found
Implementation of
getQueueStatistics()
getQueueStatistics(
queue?):Promise<QueueStatistics>
Defined in: connection.ts:998
Get statistics for a queue
Parameters
queue?
string
Optional queue name (if omitted, gets stats for all queues)
Returns
Promise<QueueStatistics>
Promise that resolves to queue statistics
Implementation of
isClientShuttingDown()
isClientShuttingDown():
boolean
Defined in: connection.ts:1519
Check if client is shutting down
Returns
boolean
True if the client is in the process of shutting down
Implementation of
Connection.isClientShuttingDown
listDLQMessages()
listDLQMessages():
Promise<DLQMessage[]>
Defined in: connection.ts:1059
List messages in the Dead Letter Queue
Returns
Promise<DLQMessage[]>
Promise that resolves to a list of DLQ messages
Implementation of
listMessages()
listMessages(
queue):Promise<QueueMessage[]>
Defined in: connection.ts:1141
List all messages in a queue
Parameters
queue
string
The queue name
Returns
Promise<QueueMessage[]>
Promise that resolves to a list of queue messages
Implementation of
listQueues()
listQueues():
Promise<QueueInfo[]>
Defined in: connection.ts:975
List all queues
Returns
Promise<QueueInfo[]>
Promise that resolves to a list of queue information
Implementation of
listTopics()
listTopics():
Promise<string[]>
Defined in: connection.ts:960
List all topics
Returns
Promise<string[]>
Promise that resolves to a list of topic names
Implementation of
maintenanceFast()
maintenanceFast():
Promise<{inactiveQueuesDropped:number;retiredToDlq:number; }>
Defined in: connection.ts:1038
Bundle the latency-sensitive maintenance routines into one call: retire crashed-final-attempt rows to DLQ + reap expired exclusive queues. Run on a 30-60 second cron (≤ ½ × the shortest keepAliveInterval in your queues so dead exclusive queues are reaped within ~1.5× their interval).
nack_message already retires the final attempt inline; this only catches rows whose consumer crashed mid-handler. cleanup_completed_messages stays separate — it's a latency-tolerant bulk DELETE governed by retention policy.
Returns
Promise<{ inactiveQueuesDropped: number; retiredToDlq: number; }>
Implementation of
off()
off(
event,listener):void
Defined in: connection.ts:1544
Unsubscribe a previously registered connection-level event listener.
Parameters
event
string
The event name
listener
(...args) => void
The callback to remove
Returns
void
on()
on(
event,listener):void
Defined in: connection.ts:1534
Subscribe to a connection-level event. Currently emits:
- 'queueFatal' (queue: string, error: QueueFatalError): the queue is gone (deleted out-of-band, or an exclusive queue whose keep-alive permanently failed) and any consumers on it have been torn down. Consumers also learn via Consumer.onClose; this is the only signal for a producer-only exclusive queue with no consumer.
Parameters
event
"queueFatal"
The event name
listener
(queue, error) => void
The callback
Returns
void
publish()
publish(
topic,payload,options?):Promise<number>
Defined in: connection.ts:690
Publish a message to a topic
Parameters
topic
string
The topic name
payload
any
The message payload
options?
PublishOptions = {}
Publishing options
Returns
Promise<number>
Promise resolving to the message ID
Implementation of
publishWithTransaction()
publishWithTransaction(
tx,topic,payload,options?):Promise<number>
Defined in: connection.ts:748
Publish a message within an existing transaction.
Runs publish_message on the caller-supplied transaction so the publish commits (or rolls back) atomically with the caller's other writes — e.g. insert an order row and enqueue its "order.created" event in one unit. The distribution trigger fires inside the transaction, so the message only reaches queues if the transaction commits.
Unlike publish(), this does NOT apply the internal retry policy: retry boundaries belong to the caller, who owns BEGIN / COMMIT / ROLLBACK. A retry here could replay the INSERT against an already-aborted or already-committed transaction. The caller is responsible for retrying the whole transaction on a serialization failure.
Parameters
tx
An object exposing query(text, values) bound to an open
transaction — a pg PoolClient/Client after BEGIN satisfies
this. Mirrors the tx accepted by Message.ackWithTransaction.
topic
string
The topic name (must already exist)
payload
any
The message payload
options?
PublishOptions = {}
Publishing options (e.g. deliverAfter for delayed delivery)
Returns
Promise<number>
Promise resolving to the message ID
Example
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('INSERT INTO orders ...');
const id = await connection.publishWithTransaction(
client, 'orders', { orderId: 42 });
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
Implementation of
Connection.publishWithTransaction
purgeAllMessages()
purgeAllMessages():
Promise<void>
Defined in: connection.ts:1109
Delete all delivery rows, dead letters, and published payloads across all topics and queues. Preserve topic and queue definitions.
Returns
Promise<void>
Promise that resolves when all messages are purged
Implementation of
purgeDLQ()
purgeDLQ():
Promise<void>
Defined in: connection.ts:1095
Purge all messages from the Dead Letter Queue
Returns
Promise<void>
Promise that resolves when DLQ is purged
Implementation of
requeueDLQMessages()
requeueDLQMessages(
queue):Promise<void>
Defined in: connection.ts:1081
Replay only the named queue's dead letters back into that same queue. Reset their delivery attempts to 0 and visibility time to now; FIFO ordering and other claim conditions still apply.
Parameters
queue
string
The queue name
Returns
Promise<void>
Promise that resolves when messages are requeued