I’m trying to connect into a postgresSQL database in typescript and to be faire, it doesn’t work and it’s not explicite why.
I do not have any error log output and so after trying to use manually some console.log
to debug.
I found that the method connect seem to timeout or fail I don’t know since I do not have any logs or other information.
This is what I’ve done:
import { Client } from 'pg'; import { env } from "./integration.env"; import fs from 'fs'; async function resetDatabase(): Promise<void> { const client = new Client(env.database); console.log("before connect"); // only output That I got await client.connect(); console.log("after connect"); // not displayed :( const res = await client.query(fs.readFileSync("./seed.sql"), ['Connection to postgres successful!']); console.log("connected", res.rows[0].connected); // not displayed :( await client.end(); } resetDatabase().then((a) => console.log("ok", a)).catch(a => console.log("no", a)); // thoses logs are not displayed :(
I run this code with the command npx ts-node test
and the only output I get is before connect
It doesn’t even display the ok or the no at the end of the promise and so I really don’t know where is the problem. If the problem is the data send to the constructor to create the client, I guess the connection method will just fail with a specific error no ?
Thanks a lot for your help.
Advertisement
Answer
I was trying to do this with an old version of pg, I updated pg to the version 8.7.3
and now it works well.
by the way I also added some try catch block because If something fail after the connection it doesn’t go to the client.end();
import { Client } from 'pg'; import { env } from "./integration.env"; import fs from 'fs'; async function resetDatabase(): Promise<void> { const client = new Client(env.database); try { console.log("before connect"); await client.connect(); console.log("after connect"); const res = await client.query(fs.readFileSync("./seed.sql"), ['Connection to postgres successful!']); console.log("connected", res.rows[0].connected); } catch(err) { console.error(err); } await client.end(); } resetDatabase().then((a) => console.log("ok", a)).catch(a => console.log("no", a));