This repository has been archived by the owner on Dec 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
107 lines (87 loc) · 3.32 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
"use strict"
import events from "events";
/**
* connect to MYSQL Database..
*
* this is a long live connection and not a connection pool
*/
class mop{
static DB = '';
static DB_INFO = '';
static async register (options) {
const {
DATABASE_INFO: DATABASE_INFO = {
host: 'localhost',
user: '',
password: '',
database: ''
}
} = options;
const {WAIT_TIME: WAIT_TIME = 5000} = options;
const {MODULE: MODULE} = options;
if(MODULE === undefined){
MODULE = await import("mysql2")
}
// test connection
const connection = MODULE.createConnection(DATABASE_INFO);
const emitter = new events.EventEmitter();
// store test connection
this.DB = connection;
this.DB_INFO = emitter;
const CONNECT = async function () {
try {
// new connection
const new_connection = await new Promise(async (resolve, reject) => {
if(connection.state){
if (connection.state === "disconnected") {
const connection = MODULE.createConnection(DATABASE_INFO);
connection.connect(function (error) {
if (error) {
const code = error.code;
const message = error.message;
emitter.emit("reconnect_error", code, message)
setTimeout(CONNECT, WAIT_TIME);
} else {
resolve(connection);
}
});
} else {
reject('already connected');
}
}
else{
const connection = MODULE.createConnection(DATABASE_INFO);
connection.connect(function (error){
if (error) {
const code = error.code;
const message = error.message;
emitter.emit("reconnect_error", code, message)
setTimeout(CONNECT, WAIT_TIME);
} else {
resolve(connection);
}
})
}
});
mop.DB = new_connection;
emitter.emit("connect", true)
mop.DB.on('error', function (error) {
const code = error.code;
emitter.emit("disconnect", code)
mop.DB.destroy()
CONNECT();
});
} catch (e) {
emitter.emit("connect", true)
mop.DB.on('error', function (error) {
const code = error.code;
emitter.emit("disconnect", code);
mop.DB.destroy();
CONNECT();
});
}
}
CONNECT()
}
}
export default mop;