Skip to content

Muhammad-Magdi/pgmq-js

Repository files navigation

pgmq-js

Postgres Message Queue (PGMQ) JavaScript Client Library

version weekly downloads license

Installation

As always:

npm i pgmq-js

Usage

First, Start a Postgres instance with the PGMQ extension installed:

docker run -d --name postgres -e POSTGRES_PASSWORD=password -p 5432:5432 quay.io/tembo/pgmq-pg:v1.2.1

Then:

import { Pgmq } from 'pgmq-js';

console.log('Connecting to Postgres...');
const pgmq = await Pgmq.new(
  {
    host: 'localhost',
    database: 'postgres',
    password: 'password',
    port: 5432,
    user: 'postgres',
    ssl: false,
  },
  //  { skipExtensionCreation: true },  Set this if you want to bypass extension creation (e.g. dbdev users).
).catch((err) => {
  console.error('Failed to connect to Postgres', err);
});

const qName = 'my_queue';
console.log(`Creating queue ${qName}...`);
await pgmq.queue.create(qName).catch((err) => {
  console.error('Failed to create queue', err);
});

interface Msg {
  id: number;
  name: string;
}
const msg: Msg = { id: 1, name: 'testMsg' };
console.log('Sending message...');
const msgId = await pgmq.msg.send(qName, msg).catch((err) => {
  console.error('Failed to send message', err);
});

const vt = 30;
const receivedMsg = await pgmq.msg.read<Msg>(qName, vt).catch((err) => {
  console.error('No messages in the queue', err);
});

console.log('Received message...');
console.dir(receivedMsg.message, { depth: null });

console.log('Archiving message...');
await pgmq.msg.archive(qName, msgId).catch((err) => {
  console.error('Failed to archive message', err);
});

API

Supported Functionalities