How can I get data from a Heroku PostgreSQL database from a Google Cloud Function?

Viewed 104

Google does not offer a free PostgreSQL instance, but Heroku does. Because of that, I am wanting to use GCP for everything except the database. Is there any way to connect to a Heroku database from a Google Cloud Function?

I am new to Google Cloud and am familiar with creating and hosting Express apps. I know that with Express, packages like Massive can be used to establish connections like this:

const express = require("express");
const massive = require("massive");
const { CONNECTION_STRING } = process.env;

const app = express();
app.use(express.json());

massive({
  connectionString: CONNECTION_STRING,
  ssl: { rejectUnauthorized: false },
})
  .then((databaseInstance) => {
    app.set("database", databaseInstance);
    console.log(gradientString.pastel("DB Connected"));
  })
  .catch((error) => {
    console.log(error);
  });

but because there is no server, I am not sure how I would go about calling a Heroku database from a Cloud Function. Is that possible?

1 Answers

It is not much different in cloud functions. In the package.json file add dependency to massive:

  "dependencies": {
    "massive": "^6.10.2"
  }

Then follow instructions from Heroku to get the connection string of postgres and use that in the code you shared.

Related