summaryrefslogtreecommitdiff
path: root/source/database.js
blob: 84fc6c7d533aeba266daa4c25a3b9de154eca515 (plain)
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
const mysql = require('mysql2')
const logger = require('./logger')()
require('dotenv').config()

// Authenticates with SQL server and send query
class Database {
    constructor(x) {
        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()
    }
}

module.exports = (x) => {return new Database(x)}