Spaces:
Sleeping
Sleeping
File size: 3,008 Bytes
4c025e9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
const asyncHandler = require('express-async-handler');
const Category = require('../models/Category');
const PromptGroup = require('../models/PromptGroup');
// @desc 获取所有分类
// @route GET /api/categories
// @access Private
const getCategories = asyncHandler(async (req, res) => {
const categories = await Category.find({}).sort({ name: 1 });
res.json(categories);
});
// @desc 通过ID获取分类
// @route GET /api/categories/:id
// @access Private
const getCategoryById = asyncHandler(async (req, res) => {
const category = await Category.findById(req.params.id);
if (category) {
res.json(category);
} else {
res.status(404);
throw new Error('分类未找到');
}
});
// @desc 创建分类
// @route POST /api/categories
// @access Private
const createCategory = asyncHandler(async (req, res) => {
const { name, color } = req.body;
// 检查是否分类名称已存在
const categoryExists = await Category.findOne({ name });
if (categoryExists) {
res.status(400);
throw new Error('分类名称已存在');
}
const category = await Category.create({
name,
color: color || '#007AFF',
});
if (category) {
res.status(201).json(category);
} else {
res.status(400);
throw new Error('无效的分类数据');
}
});
// @desc 更新分类
// @route PUT /api/categories/:id
// @access Private
const updateCategory = asyncHandler(async (req, res) => {
const { name, color } = req.body;
const category = await Category.findById(req.params.id);
if (category) {
// 如果更改了名称,检查新名称是否已存在
if (name && name !== category.name) {
const categoryExists = await Category.findOne({ name });
if (categoryExists) {
res.status(400);
throw new Error('分类名称已存在');
}
}
category.name = name || category.name;
category.color = color || category.color;
const updatedCategory = await category.save();
res.json(updatedCategory);
} else {
res.status(404);
throw new Error('分类未找到');
}
});
// @desc 删除分类
// @route DELETE /api/categories/:id
// @access Private
const deleteCategory = asyncHandler(async (req, res) => {
const category = await Category.findById(req.params.id);
if (!category) {
res.status(404);
throw new Error('分类未找到');
}
// 检查是否有提示词组使用该分类
const groupsUsingCategory = await PromptGroup.countDocuments({ category: req.params.id });
if (groupsUsingCategory > 0) {
res.status(400);
throw new Error(`无法删除分类,有 ${groupsUsingCategory} 个提示词组正在使用它`);
}
await category.deleteOne();
res.json({ message: '分类已删除' });
});
module.exports = {
getCategories,
getCategoryById,
createCategory,
updateCategory,
deleteCategory,
}; |