-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
243 lines (218 loc) · 7.31 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/* istanbul ignore file */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-else-return */
const mysql = require("mysql");
const fs = require('fs');
let pools = {};
let config = {};
const genericError = 'An error occurred communicating with the database.';
exports.init = async (cfg) => {
config = cfg;
};
exports.createPool = async (poolName) => {
try {
const srcCfg = config.DATASOURCES[poolName];
if (srcCfg) {
const options = {
connectionLimit: srcCfg.DB_CONNECTION_LIMIT || 5,
host: srcCfg.DB_HOST,
user: srcCfg.DB_USER,
password: srcCfg.DB_PASSWORD,
database: srcCfg.DB_DATABASE,
port: srcCfg.PORT,
multipleStatements: srcCfg.ALLOW_MULTI_STATEMENTS || false,
timezone: srcCfg.TIMEZONE || 'local',
typeCast: srcCfg.TYPE_CAST || true,
dateStrings: srcCfg.DATE_STRINGS || false
};
if (srcCfg.SSL) {
const sslConfig = {};
if (srcCfg.SSL.CUSTOM_CERT) {
sslConfig.ca = srcCfg.SSL.CUSTOM_CERT;
} else {
sslConfig.rejectUnauthorized = srcCfg.SSL.hasOwnProperty('REJECT_UNAUTHORIZED') ? srcCfg.SSL.REJECT_UNAUTHORIZED : true;
}
options.ssl = sslConfig;
}
pools[poolName] = mysql.createPool(options);
console.debug(`MySQL Adapter: Pool ${poolName} created`);
return true;
} else {
console.error(`MySQL Adapter: Missing configuration for ${poolName}`);
return false;
}
} catch (err) {
console.error("MySQL Adapter: Error while closing connection", err);
return false;
}
};
exports.connect = async (poolName) => {
try {
if (!pools[poolName]) {
await this.createPool(poolName);
}
return pools[poolName];
} catch (err) {
console.error("MySQL Adapter: Error while retrieving a connection", err);
throw new Error(err.message);
}
};
this.query = async (conn, query, params) => {
return new Promise((resolve, reject) => {
try {
conn.query(query, params, (error, results) => {
if (error) {
console.error("MySQL Adapter: Failure in query: ", error);
this.handleError(reject, error);
} else {
resolve(results);
}
});
} catch (err) {
console.error("MySQL Adapter: Failure in query: ", err);
this.handleError(reject, err);
}
});
};
this.handleError = (reject, error) => {
const errorReturn = (config && config.HIDE_DB_ERRORS) ? new Error(genericError) : error;
reject(errorReturn);
};
exports.execute = async (srcName, query, params = {}) => {
try {
console.debug(query);
if (params) {
console.debug(JSON.stringify(params));
}
const start = process.hrtime();
const conn = await this.connect(srcName);
console.debug(
`MySQL Adapter: Connection secured: ${process.hrtime(start)[0]}s ${
process.hrtime(start)[1] / 1000000
}ms`
);
const results = await this.query(conn, query, params);
console.debug(
`MySQL Adapter: Query executed: ${process.hrtime(start)[0]}s ${
process.hrtime(start)[1] / 1000000
}ms`
);
return results;
} catch (err) {
console.error("MySQL Adapter: Error while executing query", err);
throw new Error(err.message);
}
};
exports.closeAllPools = async () => {
try {
for (const poolAlias of Object.keys(pools)) {
await this.closePool(poolAlias);
delete pools[poolAlias];
console.debug(`MySQL Adapter: Pool ${poolAlias} closed`);
}
return true;
} catch (err) {
console.error("MySQL Adapter: Error while closing connection", err);
return false;
}
};
exports.closePool = async (poolAlias) => {
try {
if (pools[poolAlias]) {
const poolConn = pools[poolAlias];
delete pools[poolAlias];
await poolConn.end((err) => {
if (err) {
console.error(
`Error while closing connection pool ${poolAlias}`,
err
);
}
});
return true;
} else {
return true;
}
} catch (err) {
console.error("MySQL Adapter: Error while closing connection", err);
return false;
}
};
exports.transactionConnection = (pool) => {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
let query;
if (err) reject(err);
if (connection) {
console.log("MySQL Pool connected with threadId " + connection.threadId);
query = (sql, params) => {
return new Promise((resolve, reject) => {
connection.query(sql, params, (err, result) => {
console.debug("Executing query " + sql);
if (params) {
console.debug(JSON.stringify(params));
}
if (err) reject(err);
resolve(result);
});
});
};
}
const TRANSACTIONS = Object.freeze({
START: 'START TRANSACTION',
COMMIT: 'COMMIT',
ROLLBACK: 'ROLLBACK'
});
const release = () => {
return new Promise((resolve, reject) => {
if (err) reject(err);
if (connection) {
console.log("MySQL pool released the thread " + connection.threadId);
resolve(connection.release());
}
});
};
const beginTransaction = () => {
return new Promise((resolve, reject) => {
if (err) reject(err);
if (connection) {
console.log("MySQL beginning transaction with connection thread: " + connection.threadId);
resolve(connection.query(TRANSACTIONS.START));
}
});
};
const commitTransaction = () => {
return new Promise((resolve, reject) => {
if (err) reject(err);
if (connection) {
console.log("MySQL commiting transaction for connection thread: " + connection.threadId);
resolve(connection.query(TRANSACTIONS.COMMIT));
}
});
};
const rollbackTransaction = () => {
return new Promise((resolve, reject) => {
if (err) reject(err);
if (connection) {
console.log("MySQL rolling back the transaction of connection thread: " + connection.threadId);
resolve(connection.query(TRANSACTIONS.ROLLBACK));
}
});
};
const execute = (sql, params) => {
return new Promise((resolve, reject) => {
connection.query(sql, params, (err, result) => {
console.debug("Executing query " + sql);
if (params) {
console.debug(JSON.stringify(params));
}
if (err) reject(err);
resolve(result);
});
});
}
resolve({ query, execute, release, beginTransaction, commitTransaction, rollbackTransaction});
});
});
};