-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
76 lines (68 loc) · 2.37 KB
/
database.js
File metadata and controls
76 lines (68 loc) · 2.37 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
71
72
73
74
75
76
const mysql = require('mysql2/promise');
class Database {
/**
* Connect to the database using mysql2
* @returns {Promise<mysql.Connection>} The connection
*/
async connect() {
console.log('Connecting to the database...');
// Await the creation of the connection
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
port: process.env.DB_PORT,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
return connection;
}
/**
* Execute a parameterized query against the database.
* @param {string} query The SQL query with named parameters (e.g., :name)
* @param {Object} params An object of parameters (e.g., { name: "jamie", id: 1 })
* @returns {Promise<*>} The query results
*/
async executeQuery(query, params = {}) {
// Convert parameters to a consistent format: add a colon prefix if missing and escape the value.
const parameters = this.escape(params);
// Replace named parameters in the query with the escaped values.
const parameterizedQuery = this.parameterize(query, parameters);
// Get a connection
const conn = await this.connect();
try {
// Execute the query; using the promise-based API, we don't need a callback.
const [results, fields] = await conn.query(parameterizedQuery);
await conn.end();
return results;
} catch (err) {
await conn.end();
throw err;
}
}
/**
* Escape values in the data object.
* @param {Object} data
* @returns {Object} Object with keys starting with a colon and escaped values.
*/
escape(data = {}) {
let output = [];
for (const [key, value] of Object.entries(data)) {
output[key] = mysql.escape(value);
}
return output;
}
/**
* Replace named parameters in the query with their escaped values.
* @param {string} query
* @param {Object} data
* @returns {string}
*/
parameterize(query, data = {}) {
let output = query;
for (const [key, value] of Object.entries(data)) {
output = output.replace(key, value);
}
return output;
}
}
module.exports = Database;