category.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const express = require('express');
  2. const router = express.Router();
  3. const { Category } = require('../models');
  4. // 获取所有顶级品类及其子类
  5. router.get('/tree', async (req, res) => {
  6. try {
  7. const categories = await Category.findAll({
  8. where: { level: 1 },
  9. include: [{
  10. model: Category,
  11. as: 'children'
  12. }],
  13. order: [
  14. ['order', 'ASC'],
  15. [{ model: Category, as: 'children' }, 'order', 'ASC']
  16. ]
  17. });
  18. res.json(categories);
  19. } catch (error) {
  20. res.status(500).json({ error: error.message });
  21. }
  22. });
  23. // 根据ID获取品类及其所有子类
  24. router.get('/:id', async (req, res) => {
  25. try {
  26. const category = await Category.findByPk(req.params.id, {
  27. include: [{
  28. model: Category,
  29. as: 'children'
  30. }]
  31. });
  32. if (!category) {
  33. return res.status(404).json({ error: '品类不存在' });
  34. }
  35. res.json(category);
  36. } catch (error) {
  37. res.status(500).json({ error: error.message });
  38. }
  39. });
  40. // 添加新品类
  41. router.post('/', async (req, res) => {
  42. try {
  43. const category = await Category.create(req.body);
  44. res.status(201).json(category);
  45. } catch (error) {
  46. res.status(500).json({ error: error.message });
  47. }
  48. });
  49. // 更新品类
  50. router.put('/:id', async (req, res) => {
  51. try {
  52. const category = await Category.findByPk(req.params.id);
  53. if (!category) {
  54. return res.status(404).json({ error: '品类不存在' });
  55. }
  56. await category.update(req.body);
  57. res.json(category);
  58. } catch (error) {
  59. res.status(500).json({ error: error.message });
  60. }
  61. });
  62. // 删除品类(会级联删除子类)
  63. router.delete('/:id', async (req, res) => {
  64. try {
  65. const category = await Category.findByPk(req.params.id);
  66. if (!category) {
  67. return res.status(404).json({ error: '品类不存在' });
  68. }
  69. await category.destroy();
  70. res.status(204).send();
  71. } catch (error) {
  72. res.status(500).json({ error: error.message });
  73. }
  74. });
  75. module.exports = router;