-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
110 lines (96 loc) · 2.57 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
const mysql = require("mysql2");
const EventEmitter = require("events");
class MysqlClient extends EventEmitter {
constructor(options) {
super();
this._events = {
Ready: "ready",
Disconnected: "disconnected",
Error: "error",
};
this._eventsCount = 3;
this._config = {
host: options.host,
user: options.user,
password: options.password,
database: options.database,
waitForConnections: true,
debug: false,
charset: options.charset ?? "UTF8MB4_TURKISH_CI",
connectionLimit: 30,
};
try {
this.pool = mysql.createPool(this._config);
this.pool.getConnection((err, connection) => {});
} catch (error) {
this.emit("error", error);
}
this.pool.once("connection", (mysql) => {
this.emit("ready", mysql);
});
this.pool.on("error", (error) => {
this.emit("error", error);
});
this.pool.on("end", (mysql) => {
this.emit("disconnected", mysql);
this.readyCount--;
});
}
async select(table, columns, condition) {
const query = `SELECT ${columns} FROM ${table} WHERE ${condition}`;
const result = await this.query(query);
return result;
}
async selectAll(table, columns) {
const query = `SELECT ${columns} FROM ${table}`;
const result = await this.query(query);
return result;
}
async selectOne(table, columns, condition) {
const result = await this.select(table, columns, condition);
if (Array.isArray(result) && result.length > 0) {
return result[0];
} else {
return null;
}
}
async insert(table, data) {
const query = `INSERT INTO ${table} SET ?`;
const result = await this.query(query, data);
return result;
}
async update(table, data, condition) {
const query = `UPDATE ${table} SET ? WHERE ${condition}`;
const result = await this.query(query, data);
return result;
}
async remove(table, condition) {
const query = `DELETE FROM ${table} WHERE ${condition}`;
const result = await this.query(query);
return result;
}
async query(sql, values) {
return new Promise((resolve, reject) => {
this.pool.getConnection((err, connection) => {
if (err) {
reject(err);
return;
}
connection.query(sql, values, (error, results) => {
connection.release();
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
});
}
destroy() {
this.pool.end();
}
}
module.exports = {
Mysql: MysqlClient,
};