Files
董海洋 0c7ed3498d Ai config
2026-05-26 13:37:55 +08:00

112 lines
2.5 KiB
JavaScript

const { query } = require('../config/database')
async function getCategories(ctx) {
const categories = await query('SELECT * FROM categories ORDER BY sort_order ASC')
ctx.body = {
code: 200,
data: categories
}
}
async function getCategoryById(ctx) {
const categoryId = parseInt(ctx.params.id)
const categories = await query('SELECT * FROM categories WHERE id = ?', [categoryId])
if (categories.length > 0) {
ctx.body = {
code: 200,
data: categories[0]
}
} else {
ctx.body = {
code: 404,
message: '分类不存在'
}
}
}
async function createCategory(ctx) {
const { name, icon, color, sortOrder = 0 } = ctx.request.body
if (!name) {
ctx.body = {
code: 400,
message: '请输入分类名称'
}
return
}
const result = await query(
'INSERT INTO categories (name, icon, color, sort_order) VALUES (?, ?, ?, ?)',
[name, icon || '', color || '#1890ff', parseInt(sortOrder)]
)
ctx.body = {
code: 200,
message: '添加成功',
data: { id: result.insertId, name, icon, color, sort_order: sortOrder }
}
}
async function updateCategory(ctx) {
const categoryId = parseInt(ctx.params.id)
const { name, icon, color, sortOrder, isShow } = ctx.request.body
if (!name) {
ctx.body = {
code: 400,
message: '请输入分类名称'
}
return
}
const result = await query(
'UPDATE categories SET name = ?, icon = ?, color = ?, sort_order = ?, is_show = ? WHERE id = ?',
[name, icon || '', color || '#1890ff', parseInt(sortOrder) || 0, parseInt(isShow) || 1, categoryId]
)
if (result.affectedRows > 0) {
ctx.body = {
code: 200,
message: '更新成功'
}
} else {
ctx.body = {
code: 404,
message: '分类不存在'
}
}
}
async function deleteCategory(ctx) {
const categoryId = parseInt(ctx.params.id)
try {
const result = await query('DELETE FROM categories WHERE id = ?', [categoryId])
if (result.affectedRows > 0) {
ctx.body = {
code: 200,
message: '删除成功'
}
} else {
ctx.body = {
code: 404,
message: '分类不存在'
}
}
} catch (error) {
console.error('删除分类失败:', error)
ctx.body = {
code: 500,
message: '删除失败,该分类下可能存在商品'
}
}
}
module.exports = {
getCategories,
getCategoryById,
createCategory,
updateCategory,
deleteCategory
}