119 lines
2.6 KiB
JavaScript
119 lines
2.6 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 recStart = (page - 1) * maxPage + 1
|
|
let recEnd = (recStart + maxPage - 1)
|
|
if (recEnd > rows) recEnd = rows
|
|
|
|
let json = {
|
|
recStart,
|
|
recEnd,
|
|
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()
|