You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
1.9 KiB
85 lines
1.9 KiB
const Product = require('../models/Product');
|
|
const { Op } = require('sequelize');
|
|
|
|
// 获取商品列表
|
|
const getProductList = async (req, res) => {
|
|
try {
|
|
// 从查询参数获取分页信息
|
|
const page = parseInt(req.query.page) || 1;
|
|
const limit = parseInt(req.query.limit) || 10;
|
|
const offset = (page - 1) * limit;
|
|
|
|
// 查询条件
|
|
const whereClause = {};
|
|
if (req.query.category) {
|
|
whereClause.category = req.query.category;
|
|
}
|
|
if (req.query.status !== undefined) {
|
|
whereClause.status = req.query.status;
|
|
}
|
|
if (req.query.name) {
|
|
whereClause.name = { [Op.like]: `%${req.query.name}%` };
|
|
}
|
|
|
|
// 查询商品列表
|
|
const { count, rows } = await Product.findAndCountAll({
|
|
where: whereClause,
|
|
limit: limit,
|
|
offset: offset,
|
|
order: [['created_at', 'DESC']]
|
|
});
|
|
|
|
return res.status(200).json({
|
|
code: 200,
|
|
msg: '获取商品列表成功',
|
|
data: {
|
|
products: rows,
|
|
pagination: {
|
|
currentPage: page,
|
|
totalPages: Math.ceil(count / limit),
|
|
totalItems: count,
|
|
itemsPerPage: limit
|
|
}
|
|
}
|
|
});
|
|
} catch (error) {
|
|
return res.status(500).json({
|
|
code: 500,
|
|
msg: '获取商品列表失败',
|
|
error: error.message
|
|
});
|
|
}
|
|
};
|
|
|
|
// 获取单个商品详情
|
|
const getProductDetail = async (req, res) => {
|
|
try {
|
|
const { id } = req.params;
|
|
|
|
const product = await Product.findByPk(id);
|
|
|
|
if (!product) {
|
|
return res.status(404).json({
|
|
code: 404,
|
|
msg: '商品不存在'
|
|
});
|
|
}
|
|
|
|
return res.status(200).json({
|
|
code: 200,
|
|
msg: '获取商品详情成功',
|
|
data: product
|
|
});
|
|
} catch (error) {
|
|
return res.status(500).json({
|
|
code: 500,
|
|
msg: '获取商品详情失败',
|
|
error: error.message
|
|
});
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
getProductList,
|
|
getProductDetail
|
|
}; |