-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.sql.js
More file actions
70 lines (58 loc) · 1.58 KB
/
connection.sql.js
File metadata and controls
70 lines (58 loc) · 1.58 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const mysql = require("mysql");
require("dotenv").config({ path: "./.env" });
const host = process.env.MYSQL_HOST_NAME;
const port = process.env.MYSQL_PORT; // Define the port from your environment variables
const user = process.env.MYSQL_USER_NAME;
const password = process.env.MYSQL_PASSWORD;
const database = process.env.MYSQL_DB_NAME;
const dbConfig = {
host,
user,
password,
port,
database,
};
// Create a MySQL pool
const pool = mysql.createPool(dbConfig);
// Function to handle fatal errors
const handleFatalError = (err) => {
console.error('Fatal error: ', err.message);
process.exit(1);
};
// Handle uncaught exceptions
process.on('uncaughtException', handleFatalError);
// Handle unhandled promise rejections
process.on('unhandledRejection', (err) => {
console.error('Unhandled Rejection: ', err.message);
});
// Function to execute queries
const runQuery = (query, params = []) => {
return new Promise((resolve, reject) => {
// Get a connection from the pool
pool.getConnection((err, connection) => {
if (err) {
return reject(err);
}
// Execute the query
connection.query(query, params, (queryErr, results) => {
// Release the connection back to the pool
connection.release();
if (queryErr) {
return reject(queryErr);
}
resolve(results);
});
});
});
};
// Close the MySQL pool on process exit
process.on('exit', () => {
pool.end((err) => {
if (err) {
console.error('Error closing the MySQL pool: ', err.message);
}
});
});
module.exports = {
runQuery,
};