diff options
| author | Mhykol <mchaeldonald62@pm.me> | 2024-05-08 04:02:36 -0400 |
|---|---|---|
| committer | Mhykol <mchaeldonald62@pm.me> | 2024-05-08 04:02:36 -0400 |
| commit | 91b47111035e3af270bda77859fff82ccb774a12 (patch) | |
| tree | f0eab5b86c4ef159663c0ca3b8681d16db0e3552 /source | |
| parent | 64cc512c47691825e7c31be3fc34f257b2f6f5df (diff) | |
Improve error handling and logging in database module
Diffstat (limited to 'source')
| -rw-r--r-- | source/database.js | 22 |
1 files changed, 19 insertions, 3 deletions
diff --git a/source/database.js b/source/database.js index 78e8a1f..84fc6c7 100644 --- a/source/database.js +++ b/source/database.js @@ -5,15 +5,31 @@ require('dotenv').config() // Authenticates with SQL server and send query class Database { constructor(x) { - this.pool = mysql.createPool({ + this.pool = this.#CreatePool(x) + this.pool.on('acquire', (connection) => {logger.Info('Connection acquired from pool')}) + } + + async Query(x) { + try { + return await this.pool.query(x) + } catch (err) { + if (err.code === 'ECONNREFUSED') { + logger.Error(`Database connection failed: ${err.message}`) + } else { + logger.Error(`Failed to query database: ${err.message}`) + } + return null + } + } + + #CreatePool(x) { + return mysql.createPool({ host: process.env.MYSQL_HOST, user: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: x }).promise() } - - async Query(x) {try {return await this.pool.query(x)} catch (err) {logger.Error(err)}} } module.exports = (x) => {return new Database(x)} |
