generated from csc301-2023-fall/deliverable-documents
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb.js
50 lines (42 loc) · 1.4 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// db.js
const { Pool } = require('pg');
const config = require('config');
const dbConfig = config.get('db');
const client = new Pool({
host: dbConfig.HOST,
user: dbConfig.USER,
port: dbConfig.PORT,
password: dbConfig.PASSWORD,
database: dbConfig.DATABASE,
max: dbConfig.MAX_CONNECTIONS,
idleTimeoutMillis: dbConfig.IDLE_TIMEOUT_MILLIS,
connectionTimeoutMillis: dbConfig.CONNECTION_TIMEOUT_MILLIS
});
/**
* Connects to the database using the client object.
* @async
* @function connectDB
* @returns {Promise<void>} - A Promise that resolves when the database is connected.
* @throws {Error} - If there is an error connecting to the database.
*/
const connectDB = async () => {
try {
// Promise that resolves when client.connect() succeeds
const connectPromise = client.connect();
// Promise that rejects after 5 seconds
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Connection timed out after 5 seconds'));
}, 5000); // Timeout after 5 seconds
});
// Race between connectPromise and timeoutPromise
await Promise.race([connectPromise, timeoutPromise]);
console.log('Database connected!');
} catch (error) {
console.error('Error connecting to database:', error);
}
};
module.exports = {
client,
connectDB,
};