-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseService.js
More file actions
118 lines (105 loc) · 2.87 KB
/
DatabaseService.js
File metadata and controls
118 lines (105 loc) · 2.87 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
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
class DatabaseService {
constructor(config) {
const _config = Object.freeze(config);
Object.defineProperty(this, 'config', { get: () => _config, enumerable: true });
}
/**
* type of database, class must extend this method
*/
get type() {
throw new Error("Invalid database type");
}
async start() {
//make sure init of the same instance will be called only once
if (this.isStarted === true) {
return;
}
else {
const started = true;
Object.defineProperty(this, 'isStarted', { get: () => started, enumerable: true });
}
}
async close() {
//make sure init of the same instance will be called only once
if (this.isClosed === true) {
return;
}
else {
const closed = true;
Object.defineProperty(this, 'isClosed', { get: () => closed, enumerable: true });
}
}
}
const mysql = require("mysql2");
function jsonDateReplacer(key, value) {
if (this[key] instanceof Date) {
const orgValue = this[key];
if (Number.isNaN(orgValue.getTime())) return null;
const escape_date_str = mysql.escape(orgValue);
return escape_date_str.substring(1, escape_date_str.length - 1);
}
return value;
}
class MySQLDatabaseService extends DatabaseService {
constructor(mysql_config) {
super(mysql_config);
const pool = mysql.createPool(mysql_config.pool);
Object.defineProperty(this, '_pool', {
value: pool,
enumerable: false,
configurable: false
})
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();
Object.defineProperty(this, '_promisePool', {
value: promisePool,
enumerable: false,
configurable: false
})
}
/**
* type of database
*/
get type() { return "mysql" };
async start() {
if (this.isStarted === true) {
return;
} else {
await super.start();
}
await this.promisePool.execute(this.config.monitor.test_sql);
}
async close() {
if (this.isClosed === true) {
return;
} else {
await super.close();
}
await this.pool.end()
}
get pool() {
return this._pool;
}
get promisePool() {
return this._promisePool;
}
/**
* escape JSON to be
*/
escapeJson(json) {
return JSON.stringify(json, jsonDateReplacer)
}
escape(value) {
return mysql.escape(value);
}
escapeId(identifier) {
return mysql.escapeId(identifier);
}
format(sql) {
return mysql.format(sql);
}
}
module.exports = {
DatabaseService: DatabaseService,
MySQLDatabaseService: MySQLDatabaseService
}