2025-09-18
商城接口
This commit is contained in:
73
routes/mall.js
Normal file
73
routes/mall.js
Normal file
@@ -0,0 +1,73 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const {getDB} = require('../database');
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* tags:
|
||||
* name: Mall
|
||||
* description: 商城模块
|
||||
*/
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const conn = await getDB()
|
||||
|
||||
const {
|
||||
page = '1',
|
||||
size = '10',
|
||||
category = '',
|
||||
keyword = '',
|
||||
} = req.query;
|
||||
|
||||
const pageNum = Math.max(1, parseInt(page) || 1);
|
||||
const pageSize = Math.max(1, Math.min(100, parseInt(size) || 10)); // 限制最大100条
|
||||
const offset = Math.max(0, (pageNum - 1) * pageSize);
|
||||
|
||||
console.log("分页参数:", {pageNum, pageSize, offset, category, keyword})
|
||||
|
||||
let whereClause = " and status = 'active'";
|
||||
if (category) {
|
||||
whereClause += ` and category = '${category}'`;
|
||||
}
|
||||
if (keyword) {
|
||||
whereClause += ` and name like '%${keyword}%'`;
|
||||
}
|
||||
|
||||
// 获取商品总数
|
||||
const [countResult] = await conn.execute(`
|
||||
select count(1) as total
|
||||
from products
|
||||
where '1 = 1' ${whereClause}
|
||||
`)
|
||||
const total = countResult[0].total;
|
||||
|
||||
// 获取商品列表
|
||||
const queryMallListSql = `
|
||||
select *
|
||||
from products
|
||||
where '1 = 1' ${whereClause}
|
||||
order by created_at desc
|
||||
limit ${pageSize} offset ${offset}
|
||||
`
|
||||
const [products] = await conn.execute(queryMallListSql)
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
products,
|
||||
pagination: {
|
||||
page: pageNum,
|
||||
size: pageSize,
|
||||
total,
|
||||
pages: Math.ceil(total / pageSize)
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('获取商品列表错误:', error);
|
||||
res.status(500).json({success: false, message: '获取商品列表失败'});
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
Reference in New Issue
Block a user