Files
buy-lite/server/app/service/db.js

42 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-12-30 11:53:48 +08:00
const Service = require("egg").Service
2022-12-30 16:03:32 +08:00
const {v4: uuid} = require("uuid");
2022-12-30 11:53:48 +08:00
class DbService extends Service {
async addOrUpdate(table, form) {
let result
if (!form.id) {//创建
2022-12-30 16:03:32 +08:00
form.id = uuid()
2022-12-30 11:53:48 +08:00
result = await this.app.mysql.insert(table, form)
} else {//更新
result = await this.app.mysql.update(table, form)
}
2022-12-30 16:03:32 +08:00
return result === 1 ? {code: 0, data: form.id} : {code: 1, data: null}
2022-12-30 11:53:48 +08:00
}
async delete(table, id) {
await this.app.mysql.delete(table, {id})
2022-12-30 16:03:32 +08:00
return {code: 0, data: null}
2022-12-30 11:53:48 +08:00
}
async detail(table, id) {
2022-12-30 16:03:32 +08:00
const data = await this.app.mysql.get(table, {id})
return {code: 0, data}
2022-12-30 11:53:48 +08:00
}
async list(table, params = {}) {
2022-12-30 16:34:57 +08:00
let {current = 0, size = 10} = params
delete params.size
delete params.current
delete params.total
2022-12-30 16:03:32 +08:00
const records = await this.app.mysql.select(table, {
2022-12-30 11:53:48 +08:00
where: params,
2022-12-30 16:34:57 +08:00
limit: size || 10, // 返回数据量
2022-12-30 16:03:32 +08:00
offset: Math.max(--current, 0), // 数据偏移量
2022-12-30 11:53:48 +08:00
})
2022-12-30 16:03:32 +08:00
const total = (await this.app.mysql.select(table, {where: params}))?.length || 0
return {code: 0, data: {records, total}}
2022-12-30 11:53:48 +08:00
}
}
module.exports = DbService