Files
dvcp-node-service/src/utils/dbUitls.js
2023-03-01 17:54:57 +08:00

96 lines
3.0 KiB
JavaScript

const mysql = require("mysql");
const dbConfig = require("../config/db");
const {v4: uuid} = require("uuid");
const dayjs = require("dayjs");
const chalk = require("chalk");
const {checkJson} = require("../tools");
const query = sql => new Promise((resolve, reject) => {
this.pool?.getConnection((err, conn) => {
if (err) {
reject(err)
} else {
conn.query(sql, (err, result) => {
if (err) {
reject(err)
} else {
conn.release()
resolve(result)
}
})
}
})
});
const insert = ({table, form}) => {
let sql
if (form.id) {//编辑
let arr = Object.keys(form).filter(e => form[e]).map(e => {
if (typeof form[e] == "object") {
if (checkJson(form[e])) form[e] = JSON.stringify(form[e]).replace(/"'/g, "\'")
else 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") {
if (checkJson(form[e])) form[e] = JSON.stringify(form[e]).replace(/"'/g, "\'")
else 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 sql
}
module.exports = {
pool: null,
init: () => {
this.pool = mysql.createPool(dbConfig)
console.log(`${chalk.bgBlue.black(" DATABASE ")} 数据库已连接`)
},
query,
list: ({table, search, con = 'name', sort}) => {
//列表查询
let total = 0, records = []
if (table) {
const {current, size = 10} = search, params = JSON.parse(JSON.stringify(search))
const conValue = params[con] || ""
delete params.current
delete params.size
delete params[con]
const sqlCon = Object.keys(params).map(e => `and ${e}='${params[e]}'`).join(" ")
return Promise.all([
query(`select 1 from ${table} where ${con} like '%${conValue}%' ${sqlCon}`).then(res => {
return total = res.length
}),
query(`select * from ${table} where ${con} like '%${conValue}%' ${sqlCon} order by ${sort||'createTime'} desc limit ${((current-1)||0)*size},${size}`).then(res => {
return records = res
})
]).then(() => {
return {records, total}
})
}
},
batchInsert({table, list}) {
return query(list.map(form => insert({table, form})).join(";"))
},
addOrUpdate: ({table, form}) => {
//新增和更新
const sql = insert({table, form})
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(" ")
}