-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
86 lines (84 loc) · 2.24 KB
/
db.js
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
77
78
79
80
81
82
83
84
85
86
const mysql = require("mysql2/promise");
const { getDatabaseCredentials } = require("db.js");
class DBManager {
/**
* @description 트랜잭션을 열고, connection을 반환한다.
* @returns {Promise<Connection>}
* @memberof DBManager
* @example
* const db = new DBManager();
* await db.openTransaction();
* try {
* const result = await db.executeQuery(sql, params);
* await db.commitTransaction();
* }
* catch(err) {
* await db.rollbackTransaction();
* }
*/
async openTransaction() {
const credentials = await getDatabaseCredentials();
console.log(credentials);
this.connection = await mysql.createConnection(credentials);
await this.connection.beginTransaction();
}
/**
* @description 쿼리를 실행한다.
* @returns {Promise<Connection>}
* @memberof DBManager
* @example
* const db = new DBManager();
* await db.openTransaction();
* try {
* const result = await db.executeQuery(sql, params);
* await db.commitTransaction();
* }
* catch(err) {
* await db.rollbackTransaction();
* }
*/
async executeQuery(sql, params) {
const [rows] = await this.connection.execute(sql, params);
return rows;
}
/**
* @description 트랜잭션을 커밋하고, connection을 종료한다.
* @returns {Promise<Connection>}
* @memberof DBManager
* @example
* const db = new DBManager();
* await db.openTransaction();
* try {
* const result = await db.executeQuery(sql, params);
* await db.commitTransaction();
* }
* catch(err) {
* await db.rollbackTransaction();
* }
*/
async commitTransaction() {
console.log("commit");
await this.connection.commit();
await this.connection.end();
}
/**
* @description 트랜잭션을 롤백하고, connection을 종료한다.
* @returns {Promise<Connection>}
* @memberof DBManager
* @example
* const db = new DBManager();
* await db.openTransaction();
* try {
* const result = await db.executeQuery(sql, params);
* await db.commitTransaction();
* }
* catch(err) {
* await db.rollbackTransaction();
* }
*/
async rollbackTransaction() {
await this.connection.rollback();
await this.connection.end();
}
}
module.exports = { DBManager };