47 lines
1.3 KiB
JavaScript
47 lines
1.3 KiB
JavaScript
const mysql = require("mysql");
|
|
const dbConfig = require("../config/db");
|
|
const query = sql => new Promise((resolve, reject) => {
|
|
this.pool?.getConnection((err, conn) => {
|
|
if (err) {
|
|
console.log(err)
|
|
} else {
|
|
conn.query(sql, (err, result) => {
|
|
if (err) {
|
|
console.log(err)
|
|
reject(err)
|
|
} else {
|
|
conn.release()
|
|
resolve(result)
|
|
}
|
|
})
|
|
}
|
|
})
|
|
});
|
|
module.exports = {
|
|
pool: null,
|
|
init: () => {
|
|
this.pool = mysql.createPool(dbConfig)
|
|
},
|
|
query,
|
|
list: ({table, search, con}) => {
|
|
let total = 0, records = []
|
|
if (table) {
|
|
const {current, size} = search, params = JSON.parse(JSON.stringify(search))
|
|
delete params.current
|
|
delete params.size
|
|
const sqlCon = Object.keys(params).map(e => `and ${e}='${params[e]}'`).join(" ")
|
|
return Promise.all([
|
|
query(`select 1 from ${table} where name like '%${con}%' ${sqlCon}`).then(res => {
|
|
return total = res.length
|
|
}),
|
|
query(`select * from ${table} where name like '%${con}%' ${sqlCon} limit ${(current-1)*size},${size}`).then(res => {
|
|
return records = res
|
|
})
|
|
]).then(() => {
|
|
return {records, total}
|
|
})
|
|
}
|
|
},
|
|
format: args => args.map(e => `${e.prop}`).join(" ")
|
|
}
|