-
Notifications
You must be signed in to change notification settings - Fork 14
/
mysql-pool.ts
60 lines (57 loc) · 1.53 KB
/
mysql-pool.ts
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
// external modules
const mysql = require("promise-mysql")
import { IConfig } from "../../app-logic/config"
import LogModelAction from "../log-model-actions/log-model-actions"
interface queryResult extends Array<any> {
insertId?: number
affectedRows?: number
}
export default class SQL {
private log = LogModelAction("sql")
private pool
constructor(private config: IConfig) {
this.pool = mysql.createPool(config.mysql)
this.init()
this.checkdb()
}
public loggedQuery(...args): queryResult {
var result = this.pool.query.apply(this.pool, arguments)
return result
}
public async query(...args): Promise<queryResult> {
var query = mysql.format(...args)
try {
var result = await this.pool.query(query)
} catch (err) {
this.log("query", { error: err.message, query })
throw err
}
this.log("query", { query, result })
return result
}
private async checkdb() {
await this.query("select 1")
if (this.config.env != "test") {
console.log("Connected to mysql")
}
}
private init() {
mysql
.createConnection({
host: this.config.mysql.host,
port: this.config.mysql.port,
user: this.config.mysql.user,
password: this.config.mysql.password,
database: "leadcoin",
})
.then(conn => {
return conn.end()
})
.catch(err => {
if (this.config.env != "test") {
console.log("Failed to connect to mysql:", err.message)
}
setTimeout(this.init, 2000)
})
}
}