封装增删改查

This commit is contained in:
aixianling
2022-07-04 09:47:51 +08:00
parent 716b80eedd
commit 5b437886eb
3 changed files with 57 additions and 0 deletions

View File

@@ -1,5 +1,6 @@
const mysql = require("mysql");
const dbConfig = require("../config/db");
const {v4: uuid} = require("uuid");
const query = sql => new Promise((resolve, reject) => {
this.pool?.getConnection((err, conn) => {
if (err) {
@@ -24,6 +25,7 @@ module.exports = {
},
query,
list: ({table, search, con}) => {
//列表查询
let total = 0, records = []
if (table) {
const {current, size} = search, params = JSON.parse(JSON.stringify(search))
@@ -42,5 +44,31 @@ module.exports = {
})
}
},
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})`)
},
format: args => args.map(e => `${e.prop}`).join(" ")
}