接口新增一个字段,新增接口无法保存,更新接口却能保存,什么原因?
新增接口
更新接口
数据库
/*
产品报价模块
cherry 2024.4
*/
const express = require('express');
const router = express.Router();
const expressJwt = require('express-jwt');
const { runLog } = require('../utils/logger');
const query = require('../utils/db');
// 新增报价
router.post('/add', expressJwt({
secret: 'SHIBANGTUSHUGUAN',
algorithms: ['HS256'],
getToken: (req) => {
return req.headers.token || null
}
}), async function (req, res) {
addOffer(req.body).then(() => {
res.json({ errMsg: '新增产品报价成功', code: 20000 });
}).catch((err) => {
runLog.error(err)
res.json({ errMsg: '新增产品报价失败', code: 50000, err: err.message });
})
});
// 获取单个报价详情
router.get('/detail', expressJwt({
secret: 'SHIBANGTUSHUGUAN',
algorithms: ['HS256'],
getToken: (req) => {
return req.headers.token || null
}
}), async function (req, res) {
let result = await getOfferById(req.query.id)
await res.json({ errMsg: 'ok', code: 20000, data: { detail: result } });
});
// 获取报价列表
router.get('/list', expressJwt({
secret: 'SHIBANGTUSHUGUAN',
algorithms: ['HS256'],
getToken: (req) => {
return req.headers.token || null
}
}), async function (req, res) {
let pageSize = Number(req.query.pageSize)
let page = Number(req.query.page)
let type = req.query.type
if (!pageSize || !page) {
res.json({ errMsg: '请传入合适的分页信息', code: 40300, err: null });
return
}
if (!type) {
res.json({ errMsg: '请传入上级目录分类信息', code: 40300, err: null });
return
}
delete req.query.pageSize
delete req.query.page
delete req.query.type
const { sqlStr, sqlParams } = formatParams(req.query, req.data.role, type)
let count = await getCount(sqlStr, sqlParams)
let result = await getOfferList(sqlStr, sqlParams, page, pageSize)
await res.json({ errMsg: 'ok', code: 20000, data: { list: result, total: count[0].total } });
});
// 修改报价
router.post('/update/:id', expressJwt({
secret: 'SHIBANGTUSHUGUAN',
algorithms: ['HS256'],
getToken: (req) => {
return req.headers.token || null
}
}), function (req, res) {
updateOffer(req.body, req.params.id).then(() => {
res.json({ errMsg: 'ok', code: 20000 });
}).catch((err) => {
res.json({ errMsg: '修改报价信息失败', code: 50000, err: err.message });
})
});
// 删除报价
router.get('/delete/:id', expressJwt({
secret: 'SHIBANGTUSHUGUAN',
algorithms: ['HS256'],
getToken: (req) => {
return req.headers.token || null
}
}), function (req, res) {
deleteOffer(req.params.id).then(() => {
res.json({ errMsg: 'ok', code: 20000 });
}).catch((err) => {
res.json({ errMsg: '删除报价信息失败', code: 50000, err: err.message });
})
});
// 新增报价
function addOffer(data) {
runLog.info('Received data:', data);
let sql = 'insert into product_offer (code,name,version_num,power,productType,price_type,currency,first_price,second_price,third_price,fourth_price,remark,pictureList,type,photo_num,create_time,update_time) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
return new Promise((resolve, reject) => {
query(sql, [data.code, data.name, data.version_num, data.power, data.productType, data.price_type, data.currency, Number(data.first_price), Number(data.second_price), Number(data.third_price), Number(data.fourth_price), data.remark, data.pictureList, data.type, data.photo_num, new Date(), new Date()], (err) => {
if (err) {
runLog.error('addOffer出错' + err)
reject(err)
} else {
runLog.info('Received data:', data)
resolve()
}
})
})
}
// 获取单个报价详情
function getOfferById(id) {
let sql = `select * from product_offer where id = ?;`
return new Promise(((resolve, reject) => {
query(sql, [id], (err, rows, fields) => {
if (err) {
runLog.error('getOfferById出错' + err)
reject(err)
} else {
runLog.info('getOfferById成功读取')
resolve(rows)
}
})
}))
}
// 处理查询参数
function formatParams(data, role, type) {
let str = ''
let params = []
if (data.length < 1) {
return { str, params }
}
Object.keys(data).forEach(key => {
if (!data[key]) return
if (key !== 'price') {
str += `${key} LIKE ? and `
params.push(`%${data[key]}%`)
} else {
let name = 'first_price'
switch (role) {
case 2: name = 'second_price'
break
case 3: name = 'third_price'
break
case 4: name = 'fourth_price'
break
}
let temp = data.price.split(',')
str += `${name} >= ? and `
str += `${name} <= ? and `
params.push(Number(temp[0]))
params.push(Number(temp[1]))
}
})
if (type) {
let typeArr = type.split(',')
let inArr = []
typeArr.forEach(item => {
inArr.push("?")
params.push(item)
})
str += `type in(${inArr.toString()})`
} else {
str = str.slice(0, -4)
}
return { sqlStr: str, sqlParams: params }
}
// 获取报价列表
function getOfferList(sqlStr, sqlParams, page, pageSize) {
let start = (page - 1) * pageSize
let sql = `select * from product_offer `
if (sqlStr) {
sql += `where ${sqlStr} limit ?, ? ;`
} else {
sql += `limit ?, ? ;`
}
return new Promise(((resolve, reject) => {
query(sql, [...sqlParams, start, pageSize], (err, rows, fields) => {
if (err) {
runLog.error('getOfferList出错' + err)
reject(err)
} else {
runLog.info('getOfferList成功读取')
resolve(rows)
}
})
}))
}
// 获取用户列表总数
function getCount(sqlStr, sqlParams) {
let sql = `select count(id) as total from product_offer `
if (sqlStr) {
sql += `where ${sqlStr}`
}
return new Promise(((resolve, reject) => {
query(sql, sqlParams, (err, rows, fields) => {
if (err) {
runLog.error('getCount出错' + err)
reject(err)
} else {
runLog.info('getCount成功读取')
resolve(rows)
}
})
}))
}
// 修改报价
function updateOffer(data, id) {
let params = []
let str = ''
Object.keys(data).forEach(key => {
if (key !== 'id' && key !== 'creat_time' && key !== 'update_time') {
str += `${key} = ?,`
params.push(data[key])
}
})
str += `update_time = ?,`
params.push(new Date())
params.push(id)
let sql = `update product_offer set ${str.slice(0, -1)} where id = ?;`
return new Promise((resolve, reject) => {
query(sql, params, (err) => {
if (err) {
runLog.error('updateOffer出错' + err)
reject(err)
} else {
runLog.info('updateOffer成功')
resolve()
}
})
})
}
// 删除报价
function deleteOffer(id) {
let sql = 'delete from product_offer where id = ?;'
return new Promise((resolve, reject) => {
query(sql, [id], (err) => {
if (err) {
runLog.error('deleteOffer出错' + err)
reject(err)
} else {
runLog.info('deleteOffer成功')
resolve()
}
})
})
}
module.exports = router;
回复
1个回答
test
2024-06-25
字段名的命名规则统一成 Snake Case格式
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容