97 lines
2.9 KiB
JavaScript
97 lines
2.9 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 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.entries(form).map(([e, v]) => {
|
|
if (v) {
|
|
if (typeof v == "object") {
|
|
v = JSON.stringify(v)
|
|
v = v.replace(/(')/g, "\\$1")
|
|
}
|
|
} else v = ''
|
|
return `${e}='${v}'`
|
|
})
|
|
sql = `update ${table} set ${arr.join(",")} where id='${form.id}'`
|
|
} else {//新增
|
|
let cols = [], arr = []
|
|
Object.entries(form).map(([e, v]) => {
|
|
if (v) {
|
|
cols.push(e)
|
|
if (typeof v == "object") {
|
|
v = JSON.stringify(v)
|
|
v = v.replace(/(')/g, "\\$1")
|
|
}
|
|
arr.push(`'${v}'`)
|
|
}
|
|
})
|
|
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(" ")
|
|
}
|