webio-node/libs/mysql_pool.js

91 lines
2.1 KiB
JavaScript

const mysql = require('mysql');
const config = require('../config.json');
class MySQLPool {
constructor() {
this._user = '';
this._password = '';
this._host = '';
this._port = 3306;
this._database = '';
this._socketPath = '/var/lib/mysql/mysql.sock'
this._pool = null;
this.autoclose = false;
}
createPool(){
this._pool = mysql.createPool({
connectionLimit: 30,
user: this._user,
password: this._password,
host: this._host,
port: this._port,
socketPath: this._socketPath
});
}
async getConn() {
return new Promise((resolve, reject) => {
this._pool.getConnection((err, conn) => {
if(err) return reject(err);
return resolve(conn)
})
})
}
formatQuery(query, arg) {
return mysql.format(query, arg);
}
escape(val) {
return mysql.escape(val);
}
recordPage(rows, page, maxPage) {
if (!page || !isFinite(page) || page < 1) page = 1;
let totalpage = Math.ceil(rows / maxPage);
let prevpage = page - 1;
let nextpage = page + 1;
if (prevpage < 1) prevpage = 1;
if (nextpage > totalpage) nextpage = totalpage;
let rec_start = (page - 1) * maxPage + 1
let rec_end = (rec_start + maxPage - 1);
if (rec_end > rows) rec_end = rows;
let json = {
rec_start,
rec_end,
total: rows,
prevpage,
nextpage,
totalpage,
page
};
return json;
}
set user(str) { this._user = str; }
set host(str) { this._host = str; }
set password(str) { this._password = str; }
set port(str) { this._port = str; }
set database(str) { this._database = str; }
}
let Pool = (()=>{
let pool = new MySQLPool();
pool.user = config.db.user;
pool.password = config.db.pass;
pool.host = config.db.host;
pool.port = config.db.port;
pool.createPool();
return pool
})()
module.exports = Pool;