timgit / pg-boss

Queueing jobs in Postgres from Node.js like a boss
MIT License
2.15k stars 160 forks source link

Would you be open to supporting a conn pool object during initialization (instead of conn string) #518

Closed kevbook closed 3 weeks ago

kevbook commented 3 weeks ago

This enables us to use this in serverless environments. Below uses websockets internally

import { Pool } from '@neondatabase/serverless';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const posts = await pool.query('SELECT * FROM posts WHERE id =$1', [postId]);
pool.end();

Basically, it kind of bypasses .db.js

kevbook commented 3 weeks ago

Just in case, that's too much of a change, node postgres driver works for serverless too, especially for cloudflare workers. I think this would "mostly" be a drop-in replacement

timgit commented 3 weeks ago

The db prop in the constructor is for bypassing the internal driver. Have you tried this?

kevbook commented 3 weeks ago

Ah, that makes sense, this works locally. I'll test it on the edge

import { neon } from '@neondatabase/serverless';
import PgBoss from 'pg-boss';
import { Config } from '$config/config';

// Create a postgres client and ensure connection (send a ping)
const postgres = neon(Config.pgBoss.connString, {
  fullResults: true,
  fetchOptions: { priority: 'high' },
});

const boss = new PgBoss({
  application_name: Config.service.name,
  migrate: false,
  db: {
    executeSql: async function (text: string, values: any[]) {
      return postgres(text, values);
    },
  },
});

const id = await boss.send('help-me', { hello: 'world' });
console.log(`created job: ${id}`);