Files
dvcp-node-service/src/utils/dbUitls.js
2022-07-14 11:51:29 +08:00

79 lines
2.4 KiB
JavaScript

const mysql = require("mysql");
const dbConfig = require("../config/db");
const {v4: uuid} = require("uuid");
const dayjs = require("dayjs");
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)||0)*size},${size||10}`).then(res => {
return records = res
})
]).then(() => {
return {records, total}
})
}
},
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,createTime,${cols.join(",")}) values('${uuid()}','${dayjs().format("YYYY-MM-DD hh:mm:ss")}',${arr.join(",")})`
}
return query(sql)
},
delete: ({table, ids}) => {
ids = ids?.split(",")?.map(e => `'${e}'`)?.toString()
return query(`delete from ${table} where id in (${ids})`)
},
detail: ({table, id}) => {
return query(`select * from ${table} where id='${id}' limit 0,1`).then(res => res?.[0])
},
format: args => args.map(e => `${e.prop}`).join(" ")
}