promptbackend / controllers /categoryController.js
samlax12's picture
Upload 19 files
4c025e9 verified
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,
};