68 lines
2.2 KiB
JavaScript
68 lines
2.2 KiB
JavaScript
const express = require('express');
|
|
const { getDB } = require('../database');
|
|
const router = express.Router();
|
|
|
|
|
|
/**
|
|
* @swagger
|
|
* /api/category:
|
|
* get:
|
|
* summary: 获取一级分类及其二级分类
|
|
* description: 返回所有一级分类,每个一级分类包含其下的二级分类
|
|
* tags: [category]
|
|
* responses:
|
|
* 200:
|
|
* description: 成功返回一级分类及其二级分类
|
|
* content:
|
|
* application/json:
|
|
* schema:
|
|
* type: object
|
|
* properties:
|
|
* success:
|
|
* type: boolean
|
|
* example: true
|
|
* data:
|
|
* type: array
|
|
* items:
|
|
* type: object
|
|
* properties:
|
|
* name:
|
|
* type: string
|
|
* example: "一级分类1"
|
|
* relative:
|
|
* type: array
|
|
* items:
|
|
* type: object
|
|
* properties:
|
|
* name:
|
|
* type: string
|
|
* example: "二级分类1-1"
|
|
* img:
|
|
* type: string
|
|
* example: "https://example.com/image.jpg"
|
|
*/
|
|
router.get('/', async (req, res) => {
|
|
try {
|
|
const db = await getDB();
|
|
const [firstCategory] = await db.query('SELECT * FROM category WHERE level = 1');
|
|
|
|
|
|
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,
|
|
img: secondCategory.image,
|
|
}))
|
|
}))});
|
|
} catch (error) {
|
|
console.error('Error fetching categories:', error);
|
|
res.status(500).json({ success: false, error: 'Internal server error' });
|
|
}
|
|
});
|
|
|
|
module.exports = router; |