一个列表接口,目前是这样写 我感觉我要疯了,求优化方案
router.post('/list', (req, res) => {
let params = req.body;
// SQL
let sql = `
SELECT
*
FROM
content
`;
if(params.cityId){
sql = sql + ` WHERE cityId='${params.cityId}'`;
// 县
if(params.regionId){
sql = sql + ` and regionId='${params.regionId}'`;
}
// 按时间
if(params.filter == '1'){
sql = sql + ` order by modifTime ${params.order}`;
}
// 按点赞
if(params.filter == '2'){
sql = sql + ` order by zan ${params.order}`;
}
// 按收藏
if(params.filter == '3'){
sql = sql + ` order by collect ${params.order}`;
}
// 按评论
if(params.filter == '4'){
sql = sql + ` order by commentNum ${params.order}`;
}
// 按价格
if(params.filter == '5'){
sql = sql + ` order by price ${params.order}`;
}
// 分页
let pageSize = 20;
let pageNum = (params.pageNum -1)*pageSize;
sql = sql + ` limit ${pageNum},${pageSize}`;
}
// 执行
$db.query(sql)
.then(data=>{
// 返回给前端
res.json({
code:200,
msg:"操作成功",
data:data
});
res.end();
})
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…