aboutsummaryrefslogtreecommitdiff
path: root/db.js
blob: 244e9a6310ad29e21371255343ea03b55c15281e (plain) (blame)
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
const mariadb = require("mariadb");
const fs = require("fs");

class DB {
    constructor() {
        this.pool = mariadb.createPool({
            host: process.env.DBHost,
            user: process.env.DBUser,
            password: process.env.DBPassword,
            database: process.env.DBName,
        });
        this.init();
    }

    connect() {
        return this.pool.getConnection();
    }

    init() {
        fs.readFile(__dirname + "/tables.sql", "utf8", async (err, data) => {
            if (err) throw err;
            const queries = data.split(";");
            queries.pop();
            const conn = await this.connect();
            for (const query of queries) await conn.query(query);
            console.log("Tables created!");
        });
    }

    async query(query, params) {
        const conn = await this.connect();
        try {
            return await conn.query(query, params);
        } catch (e) {
            throw e;
        } finally {
            conn.release();
        }
    }
}

module.exports = new DB();