37 lines
945 B
JavaScript
37 lines
945 B
JavaScript
|
|
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;
|