Files
dvcp-node-service/src/utils/dbUitls.js

78 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-03-29 15:04:07 +08:00
const mysql = require("mysql");
const dbConfig = require("../config/db");
2022-07-04 09:47:51 +08:00
const {v4: uuid} = require("uuid");
2022-07-02 15:15:05 +08:00
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)
}
})
}
})
});
2022-03-29 15:04:07 +08:00
module.exports = {
pool: null,
init: () => {
this.pool = mysql.createPool(dbConfig)
},
2022-07-02 15:15:05 +08:00
query,
list: ({table, search, con}) => {
2022-07-04 09:47:51 +08:00
//列表查询
2022-07-02 15:15:05 +08:00
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
}),
2022-07-02 15:16:30 +08:00
query(`select * from ${table} where name like '%${con}%' ${sqlCon} limit ${(current-1)*size},${size||10}`).then(res => {
2022-07-02 15:15:05 +08:00
return records = res
2022-03-29 15:04:07 +08:00
})
2022-07-02 15:15:05 +08:00
]).then(() => {
return {records, total}
})
}
},
2022-07-04 09:47:51 +08:00
addOrUpdate: ({table, form}) => {
//新增和更新
let sql
if (form.id) {//编辑
let arr = Object.keys(form).filter(e => form[e]).map(e => {
if (typeof form[e] == "object") form[e] = JSON.stringify(form[e])
return `${e}='${form[e]}'`
})
sql = `update ${table} set ${arr.join(",")} where id='${form.id}'`
} else {//新增
let cols = [], arr = []
Object.keys(form).map(e => {
if (form[e]) {
cols.push(e)
if (typeof form[e] == "object") form[e] = JSON.stringify(form[e])
arr.push(`'${form[e]}'`)
}
})
sql = `insert into ${table} (id,${cols.join(",")}) values('${uuid()}',${arr.join(",")})`
}
return query(sql)
},
delete: ({table, ids}) => {
ids = ids?.split(",")?.map(e => `'${e}'`)?.toString()
return query(`delete from ${table} where id in (${ids})`)
},
2022-07-04 10:01:33 +08:00
detail: ({table, id}) => {
return query(`select * from ${table} where id='${id}' limit 0,1`)
},
2022-07-02 15:15:05 +08:00
format: args => args.map(e => `${e.prop}`).join(" ")
2022-03-29 15:04:07 +08:00
}