mysqli/index.js

76 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2017-02-28 18:27:38 +08:00
/**
* mysql操作类
2020-11-24 21:11:45 +08:00
* @author yutent<yutent.io@gmail.com>
* @date 2020/11/24 20:04:20
2017-02-28 18:27:38 +08:00
*/
2020-11-24 21:11:45 +08:00
2018-05-29 02:42:12 +08:00
require('es.shim')
2017-12-14 16:36:39 +08:00
const mysql = require('mysql')
2018-05-29 02:42:12 +08:00
const Api = require('./lib/api')
2017-12-14 16:36:39 +08:00
class Mysqli {
/**
* [constructor 构造数据库连接池]
*/
2018-05-29 02:42:12 +08:00
constructor(config) {
2017-12-14 16:36:39 +08:00
if (!Array.isArray(config)) {
config = [config]
2017-02-28 18:27:38 +08:00
}
2017-12-14 16:36:39 +08:00
//是否有从库
this.useSlaveDB = config.length > 1
this.pool = mysql.createPoolCluster({
removeNodeErrorCount: 1, // 连续失败立即从节点中移除, 并在10秒后尝试恢复
restoreNodeTimeout: 10000
})
2017-12-14 16:36:39 +08:00
2018-05-29 02:42:12 +08:00
config.forEach((item, i) => {
2018-03-22 16:37:38 +08:00
let {
host,
port,
user,
2024-07-23 18:54:00 +08:00
charset = 'utf8mb4',
2018-03-22 16:37:38 +08:00
passwd: password,
db: database,
timezone,
supportBigNumbers,
...others
2018-03-22 16:37:38 +08:00
} = item
2017-12-14 16:36:39 +08:00
let name = i < 1 ? 'MASTER' : 'SLAVE' + i
2018-03-22 16:37:38 +08:00
let collate
2017-12-14 16:36:39 +08:00
2018-03-22 16:37:38 +08:00
collate =
2020-11-24 21:11:45 +08:00
charset + (charset === 'utf8mb4' ? '_0900_ai_ci' : '_general_ci')
2017-12-14 16:36:39 +08:00
2018-03-22 16:37:38 +08:00
timezone = timezone || 'local'
supportBigNumbers = !!supportBigNumbers
2017-12-14 16:36:39 +08:00
this.pool.add(name, {
host,
port,
user,
charset,
collate,
password,
2018-03-22 16:56:47 +08:00
database,
timezone,
supportBigNumbers,
...others
2017-12-14 16:36:39 +08:00
})
})
return this
}
//对外的escape方法
2018-05-29 02:42:12 +08:00
static escape(val) {
2017-12-14 16:36:39 +08:00
return mysql.escape(val)
}
2018-05-29 02:42:12 +08:00
emit(fromSlave = false, db = '') {
let slave = fromSlave && this.useSlaveDB ? 'SLAVE*' : 'MASTER'
return new Api(this.pool, slave, db)
2017-12-14 16:36:39 +08:00
}
2017-02-28 18:27:38 +08:00
}
2017-12-14 16:36:39 +08:00
module.exports = Mysqli