119 lines
2.9 KiB
JavaScript
119 lines
2.9 KiB
JavaScript
const mysql = require('mysql');
|
|
|
|
class MySQLPool {
|
|
constructor() {
|
|
this._user = '';
|
|
this._password = '';
|
|
this._host = '';
|
|
this._port = 3306;
|
|
this._database = '';
|
|
this._socketPath = ''
|
|
this._pool = null;
|
|
this.autoclose = false;
|
|
this._useSocket = false;
|
|
}
|
|
|
|
createPool() {
|
|
let json = {
|
|
connectionLimit: 30,
|
|
user: this._user,
|
|
password: this._password,
|
|
host: this._host,
|
|
port: this._port,
|
|
socketPath: this._socketPath
|
|
};
|
|
if (this._useSocket) {
|
|
delete json.host;
|
|
delete json.port;
|
|
} else {
|
|
delete json.socketPath;
|
|
}
|
|
this._pool = mysql.createPool(json);
|
|
}
|
|
|
|
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 = ((opts) => {
|
|
// let defOpts = {
|
|
// user: 'root',
|
|
// pass: '',
|
|
// host: 'localhost',
|
|
// port: 3306,
|
|
// socket: '/var/lib/mysql/mysql.sock',
|
|
// useSocket: false
|
|
// }
|
|
|
|
// let opt = {
|
|
// user: opts.user || defOpts.user,
|
|
// pass: opts.pass || defOpts.pass,
|
|
// host: opts.host || defOpts.host,
|
|
// port: opts.port || defOpts.port,
|
|
// socket: opts.socket || defOpts.socket,
|
|
// useSocket: opts.useSocket || defOpts.useSocket
|
|
// };
|
|
|
|
// let pool = new MySQLPool();
|
|
|
|
// pool._host = opt.host;
|
|
// pool._password = opt.pass;
|
|
// pool._port = opt.port;
|
|
// pool._user = opt.user;
|
|
// pool._socket = opt.socket;
|
|
// pool._useSocket = opt.useSocket;
|
|
|
|
// pool.createPool();
|
|
// return pool
|
|
// })()
|
|
|
|
module.exports = new MySQLPool(); |