0

I have a remote server which is running my node.js code as well as a postgres server. When I connect to the postgres server from my local machine it works with CLI as well as in node code. However, when I push the same code to the server, it keeps on timing out and doesn't connect to the postgres server. Here is the code snippet

const { Pool } = require("pg");
const conn = {
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  connectionTimeoutMillis: 5000,
  port: parseInt(process.env.DB_PORT),
};
console.log(conn);
const pool = new Pool(conn);

app.post(
  "/api/v1/data/sync",
  asyncHandler(async (req, res) => {
    const { data } = req.body;

    try {
      const tasks = [];

      for (let i = 0; i < data.length; i++) {
        const query = {
          text:
            "INSERT INTO health_data(date, user_id, health_data) VALUES($1, $2, $3)",
          values: [
            data[i].date,
            data[i]["user_id"],
            data[i]["health_data"],
          ],
        };
        tasks.push(pool.query(query));
      }
      const results = await Promise.all(tasks);
      console.log("saved data");
      await pool.end();
      res.status(200).send("Data Saved");
    } catch (e) {
      console.log(e);
      res.status(500).send("error in saving data");
    }
  })
);

I tried keeping env vars same for local and server, the code works in local but doesn't in server. What am I missing here? Although I am able to use psql with same credentials in server too. It's only the node code which doesn't work.

Update

I switched the module from pg to pg-promise and same env variables work in server too. Is there any constraints about what is a valid user/password/dbname with pg module?

Rishabh Jain
  • 526
  • 1
  • 10
  • 26
  • On a related issue, inserting multiple records like this is very inefficient. Since you have switched to `pg-promise`, check out [Multi-row insert with pg-promise](https://stackoverflow.com/questions/37300997/multi-row-insert-with-pg-promise). – vitaly-t Sep 04 '20 at 19:42
  • Thanks!. Will check that out – Rishabh Jain Sep 04 '20 at 22:06

0 Answers0