接口更改
This commit is contained in:
37
routes/category.js
Normal file
37
routes/category.js
Normal file
@@ -0,0 +1,37 @@
|
||||
const express = require('express');
|
||||
const { getDB } = require('../database');
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const db = await getDB();
|
||||
const [firstCategory] = await db.query('SELECT * FROM category WHERE level = 1');
|
||||
|
||||
console.log(firstCategory);
|
||||
|
||||
for (const category of firstCategory) {
|
||||
const [secondCategories] = await db.query('SELECT * FROM category WHERE parent_id = ?', [category.id]);
|
||||
category.relative = secondCategories;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
res.json({ success: true, data: firstCategory.map(category => ({
|
||||
name: category.category_name,
|
||||
relative: category.relative.map(secondCategory => ({
|
||||
name: secondCategory.category_name,
|
||||
}))
|
||||
}))});
|
||||
} catch (error) {
|
||||
console.error('Error fetching categories:', error);
|
||||
res.status(500).json({ success: false, error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,10 +1,9 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { getDB } = require('../database');
|
||||
const { auth } = require('../middleware/auth');
|
||||
|
||||
|
||||
router.get('/', auth, async (req, res) => {
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const db = getDB();
|
||||
const query = `
|
||||
@@ -21,9 +20,10 @@ router.get('/', auth, async (req, res) => {
|
||||
res.status(500).json({ error: '获取优惠券失败' });
|
||||
}
|
||||
});
|
||||
router.get('/:id', auth, async (req, res) => {
|
||||
router.get('/:id', async (req, res) => {
|
||||
try {
|
||||
const userId = req.params.id;
|
||||
const couponId = req.body.coupon_id;
|
||||
const db = getDB();
|
||||
const query = `
|
||||
SELECT * FROM coupon_products where remain > 0
|
||||
@@ -34,12 +34,21 @@ router.get('/:id', auth, async (req, res) => {
|
||||
return res.status(404).json({ error: '暂无优惠券' });
|
||||
} else {
|
||||
const query = [`
|
||||
update coupon_products set remain = remain - 1 where id = ?
|
||||
select * from coupon_use where user_id = ?
|
||||
`,`
|
||||
insert into coupon_use (user_id, coupon_id, get_time) values (?, ?, now())
|
||||
update coupon_products set remain = remain - 1 where id = ?
|
||||
`,`
|
||||
insert into coupon_use (user_id, coupon_id, get_time) values (?, ?, now())
|
||||
`]
|
||||
await db.query(query[0], [coupon[0].id]);
|
||||
await db.query(query[1], [userId, coupon[0].id]);
|
||||
const [checkUser] = await db.query(query[0], [userId]);
|
||||
console.log("12345",checkUser)
|
||||
for (const item of checkUser) {
|
||||
if (item.coupon_id === coupon[0].id && item.use_time === null) {
|
||||
return res.status(400).json({ error: '优惠券已领取' });
|
||||
}
|
||||
}
|
||||
await db.query(query[1], [coupon[0].id]);
|
||||
await db.query(query[2], [userId, coupon[0].id]);
|
||||
}
|
||||
|
||||
res.json({coupon, success: true});
|
||||
|
||||
@@ -13,6 +13,7 @@ router.get('/', async (req, res) => {
|
||||
const pageNum = Math.max(1, parseInt(page) || 1);
|
||||
const limitNum = Math.max(1, Math.min(100, parseInt(limit) || 10)); // 限制最大100条
|
||||
const offset = Math.max(0, (pageNum - 1) * limitNum);
|
||||
let filteredProducts = []
|
||||
|
||||
console.log('分页参数:', { pageNum, limitNum, offset, search, category, status });
|
||||
|
||||
@@ -24,11 +25,6 @@ router.get('/', async (req, res) => {
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
if (category) {
|
||||
whereClause += ' AND category = ?';
|
||||
params.push(category);
|
||||
}
|
||||
|
||||
if (status) {
|
||||
whereClause += ' AND status = ?';
|
||||
params.push(status);
|
||||
@@ -43,7 +39,7 @@ router.get('/', async (req, res) => {
|
||||
|
||||
// 获取商品列表
|
||||
const query = `
|
||||
SELECT id, name, rongdou_price, category, points_price, stock, image_url as image, description, status, payment_methods, created_at, updated_at, sales
|
||||
SELECT id, name, rongdou_price, points_price, stock, image_url as image, description, status, payment_methods, created_at, updated_at, sales
|
||||
FROM products
|
||||
${whereClause}
|
||||
ORDER BY created_at DESC
|
||||
@@ -54,13 +50,42 @@ router.get('/', async (req, res) => {
|
||||
const queryParams = [...params];
|
||||
console.log('Query params:', queryParams, 'Query:', query);
|
||||
const [products] = await getDB().execute(query, queryParams);
|
||||
|
||||
products.forEach(item=>{
|
||||
item.payment_methods = JSON.parse(item.payment_methods)
|
||||
})
|
||||
|
||||
|
||||
if (category) {
|
||||
// 先根据分类名称获取分类ID
|
||||
const query = `SELECT * FROM category WHERE category_name = ?`
|
||||
const [getCategory] = await getDB().execute(query, [category])
|
||||
const [getSecondCategory] = await getDB().execute('SELECT * FROM category WHERE parent_id = ?', [getCategory[0].id])
|
||||
|
||||
const sumCategory = getCategory.concat(getSecondCategory).map(item=>item.id)
|
||||
|
||||
// 再根据分类ID获取商品ID
|
||||
const getProductCategory = []
|
||||
for (const item of sumCategory) {
|
||||
const [getProductCategoryItem] = await getDB().execute('SELECT * FROM products_category WHERE category_id = ?', [item])
|
||||
getProductCategory.push(...getProductCategoryItem)
|
||||
}
|
||||
|
||||
const productIds = []
|
||||
for (const item of getProductCategory) {
|
||||
productIds.push(item.product_id)
|
||||
}
|
||||
|
||||
filteredProducts = products.filter(item=>productIds.includes(item.id))
|
||||
} else {
|
||||
filteredProducts = products
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
products,
|
||||
products: filteredProducts,
|
||||
// products: products,
|
||||
pagination: {
|
||||
page: pageNum,
|
||||
limit: limitNum,
|
||||
@@ -75,31 +100,31 @@ router.get('/', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 获取商品分类列表
|
||||
router.get('/categories', async (req, res) => {
|
||||
try {
|
||||
const [categories] = await getDB().execute(
|
||||
'SELECT DISTINCT category FROM products WHERE status = "active" AND category IS NOT NULL'
|
||||
);
|
||||
// // 获取商品分类列表
|
||||
// router.get('/categories', async (req, res) => {
|
||||
// try {
|
||||
// const [categories] = await getDB().execute(
|
||||
// 'SELECT DISTINCT category FROM products WHERE status = "active" AND category IS NOT NULL'
|
||||
// );
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
categories: categories.map(item => item.category)
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('获取商品分类失败:', error);
|
||||
res.status(500).json({ success: false, message: '获取商品分类失败' });
|
||||
}
|
||||
});
|
||||
// res.json({
|
||||
// success: true,
|
||||
// data: {
|
||||
// categories: categories.map(item => item.category)
|
||||
// }
|
||||
// });
|
||||
// } catch (error) {
|
||||
// console.error('获取商品分类失败:', error);
|
||||
// res.status(500).json({ success: false, message: '获取商品分类失败' });
|
||||
// }
|
||||
// });
|
||||
|
||||
// 获取热销商品
|
||||
router.get('/hot', async (req, res) => {
|
||||
try {
|
||||
// 从活跃商品中随机获取2个商品
|
||||
const [products] = await getDB().execute(
|
||||
`SELECT id, name, category, price, points_price, rongdou_price, stock,
|
||||
`SELECT id, name, price, points_price, rongdou_price, stock,
|
||||
image_url, images, description, shop_name, shop_avatar,
|
||||
payment_methods, sales, rating, status, created_at, updated_at
|
||||
FROM products
|
||||
@@ -168,7 +193,7 @@ router.get('/cheap', async (req, res) => {
|
||||
const tempProducts = await Promise.all(products.map(async item=>{
|
||||
|
||||
const [product] = await getDB().execute(
|
||||
`SELECT id, name, category, price, points_price, rongdou_price, stock,
|
||||
`SELECT id, name, price, points_price, rongdou_price, stock,
|
||||
image_url, images, description, shop_name, shop_avatar,
|
||||
payment_methods, sales, rating, status, created_at, updated_at
|
||||
FROM products
|
||||
@@ -342,7 +367,7 @@ router.get('/:id', async (req, res) => {
|
||||
const userId = req.user?.id; // 可选的用户ID,用于检查收藏状态
|
||||
|
||||
const query = `
|
||||
SELECT id, name, category, price, points_price, rongdou_price, stock,
|
||||
SELECT id, name, price, points_price, rongdou_price, stock,
|
||||
image_url, images, videos, description, details, shop_name, shop_avatar,
|
||||
payment_methods, sales, rating, status, created_at, updated_at
|
||||
FROM products
|
||||
@@ -531,7 +556,7 @@ router.get('/:id', async (req, res) => {
|
||||
// 保持向后兼容
|
||||
points: product.points_price,
|
||||
image: product.image_url,
|
||||
tags: product.category ? [product.category] : []
|
||||
// tags: product.category ? [product.category] : []
|
||||
};
|
||||
|
||||
res.json({
|
||||
@@ -898,10 +923,9 @@ router.get('/:id/recommended', async (req, res) => {
|
||||
|
||||
// 获取同类别的其他商品作为推荐
|
||||
const query = `
|
||||
SELECT p2.id, p2.name, p2.category, p2.price, p2.points_price as points,
|
||||
SELECT p2.id, p2.name, p2.price, p2.points_price as points,
|
||||
p2.stock, p2.image_url as image, p2.description
|
||||
FROM products p1
|
||||
JOIN products p2 ON p1.category = p2.category
|
||||
WHERE p1.id = ? AND p2.id != ? AND p2.status = 'active'
|
||||
ORDER BY RAND()
|
||||
LIMIT 6
|
||||
@@ -914,7 +938,7 @@ router.get('/:id/recommended', async (req, res) => {
|
||||
const remainingCount = 6 - recommendedProducts.length;
|
||||
if (remainingCount > 0) {
|
||||
const additionalQuery = `
|
||||
SELECT id, name, category, price, points_price as points,
|
||||
SELECT id, name, price, points_price as points,
|
||||
stock, image_url as image, description
|
||||
FROM products
|
||||
WHERE id != ? AND status = 'active'
|
||||
|
||||
@@ -252,6 +252,10 @@ app.use('/api/payment', require('./routes/payment'));
|
||||
// 优惠券路由
|
||||
app.use('/api/coupon', require('./routes/coupon'));
|
||||
|
||||
// 分类路由
|
||||
app.use('/api/category', require('./routes/category'));
|
||||
|
||||
|
||||
// 前端路由 - 必须在最后,作为fallback
|
||||
app.get('/', (req, res) => {
|
||||
res.removeHeader('Origin-Agent-Cluster');
|
||||
|
||||
Reference in New Issue
Block a user