mysql-promise.js
1.3 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
'use strict';
const mysql = require('promise-mysql');
const config = require('../config/config');
class MysqlPromise {
constructor() {
this.connect();
}
connect() {
if (this.conn) {
return Promise.resolve(this.conn);
}
return mysql.createConnection({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
port: config.mysql.port,
database: config.mysql.database
}).then(conn => {
this.conn = conn;
return conn;
}).catch(err => {
console.error(`mysql connect fail, err: ${err.message}`);
return null;
});
}
query(sql, values) {
return this.connect().then(d => {
return d.query(sql, values);
}).catch(err => {
console.error(`mysql query, err: ${err.message}`);
return [];
});
}
close(data) {
return this.connect().then(d => {
return d.end();
}).then(d => {
this.conn = null;
return data;
}).catch(err => {
this.conn = null;
console.error(`mysql close, err: ${err.message}`);
return data;
});
}
}
module.exports = MysqlPromise;