Passed
Push — main ( 41db93...062dcb )
by Julia
02:58
created

server/src/models/db.js   A

Complexity

Total Complexity 7
Complexity/F 3.5

Size

Lines of Code 78
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 34
mnd 5
bc 5
fnc 2
dl 0
loc 78
ccs 20
cts 20
cp 1
bpm 2.5
cpm 3.5
noi 0
c 0
b 0
f 0
rs 10
1
import dotenv from "dotenv";
2 1
dotenv.config();
3
4
import mariadb from 'mariadb';
5
6 1
let host = process.env.DB_HOST;
7 1
let database = process.env.DB_DATABASE;
8
9
/**
10
 * Changes to test database
11
 */
12 2
if (process.env.NODE_ENV === "test") {
13 1
    host = process.env.DB_TEST_HOST;
14 1
    database = process.env.TEST_DATABASE;
15
}
16
17 1
const pool = mariadb.createPool({
18
    host: host,
19
    user: process.env.DB_USER,
20
    database: database,
21
    password: process.env.DB_PASSWORD,
22
    // connectionLimit: 10,
23
     multipleStatements: true,
24
    // namedPlaceholders: true
25
});
26
27
28 1
export const db = {
29
    /**
30
     * For handling connections
31
     * to the database
32
     */
33
    pool: pool,
34
35
    /**
36
     * For database queries without
37
     * arguments
38
     * @param {String} sql 
39
     * @returns {Promise<Array>}
40
     */
41
    queryNoArgs: async function(sql) {
42
        let conn;
43
44 19
        try {
45 19
            conn = await pool.getConnection();
46
47 19
            let res = await conn.query(sql);
48 19
            return res;
49
            // no catching error here
50
        } finally {
51 19
            if (conn) {
52 19
                conn.end();
53
            }
54
        }
55
    },
56
57
    /**
58
     * For database queries
59
     * with arguments
60
     * @param {String} sql 
61
     * @param {Array} args 
62
     * @returns {Promise<Array>}
63
     */
64
    queryWithArgs: async function(sql, args) {
65
        let conn;
66
67 159
        try {
68 159
            conn = await pool.getConnection();
69 159
            let res = await conn.query(sql, args);
70 143
            return res;
71
            // no catching error here
72
        } finally {
73 159
            if (conn) {
74 159
                conn.end();
75
            }
76
        }
77
    },
78
}