Create a Heroku Postgres Client in Node.js

For Salesforce Functions written in Node.js, use the node-postgres (pg) package to access your Heroku PostgreSQL database. Access the DATABASE_URL environment variable with process.env to create a Postgres client instance.

import { Client } from "pg";
async function pgConnect() {
  const DATABASE_URL = process.env.DATABASE_URL;
  if (!DATABASE_URL) {
    throw new Error("DATABASE_URL is not set");
  }
  // Connect to PostgreSQL
  const client = new Client({
    connectionString: DATABASE_URL,
    ssl: {
      rejectUnauthorized: false,
    },
  });

  await client.connect();
  return client;
}