0% found this document useful (0 votes)
6 views1 page

Database Example Connection

The document is a JavaScript code snippet that sets up a connection to a PostgreSQL database using the 'pg' library and environment variables. It defines a function 'connect_to_database' that attempts to connect to the database up to three times, logging errors and retrying if the connection fails. If all attempts fail, it exits the process with an error message.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Database Example Connection

The document is a JavaScript code snippet that sets up a connection to a PostgreSQL database using the 'pg' library and environment variables. It defines a function 'connect_to_database' that attempts to connect to the database up to three times, logging errors and retrying if the connection fails. If all attempts fail, it exits the process with an error message.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import { Pool } from "pg";

import dotenv from 'dotenv';

dotenv.config({ path: './config/.env' })

const pool = new Pool({


user: process.env.POSTGRES_USER,
host: process.env.POSTGRES_HOST,
database: process.env.POSTGRES_DB,
password: process.env.POSTGRES_PASSWORD,
port: Number( process.env.POSTGRES_PORT ),
});

const connect_to_database = async (): Promise<void> => {


let attemp: number = 0;
const max_attempts: number = 3

while (attemp < max_attempts) {


try {
await pool.query("SET client_encoding = 'UTF8';");
await pool.connect();
console.log("Connected to database");
return;
} catch (error) {
attemp++
console.error('error to connected to database', error);

if (attemp < max_attempts) {


console.log(`Retrying connection to database... (${attemp}/ $
{max_attempts})`);
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
console.error('Failed to connect to database after 3 attempts');
process.exit(1);
}
}
}
}

export { connect_to_database, pool };

You might also like