Files
ofertaweb.cl/backend/src/controllers/categoryController.js
cesar 2a88b4a71b Initial commit: Estructura backend y frontend con estándar VPS
- Backend migrado a estructura VPS (src/ subfolder)
- Frontend con estructura Vite + React 19 + Tailwind
- Configuración PostgreSQL con Pool
- API service con interceptores JWT
- Ambos servidores funcionando (backend:3001, frontend:5173)
2025-12-09 00:35:46 -03:00

86 lines
2.2 KiB
JavaScript

const Category = require('../models/Category');
const { asyncHandler } = require('../utils/helpers');
// Listar categorías
exports.listCategories = asyncHandler(async (req, res) => {
const { is_active, parent_id } = req.query;
const categories = await Category.list({
is_active: is_active !== undefined ? is_active === 'true' : undefined,
parent_id: parent_id ? parseInt(parent_id) : undefined
});
res.json({ categories });
});
// Obtener árbol de categorías
exports.getCategoryTree = asyncHandler(async (req, res) => {
const tree = await Category.getTree();
res.json({ categories: tree });
});
// Obtener categoría por ID
exports.getCategory = asyncHandler(async (req, res) => {
const category = await Category.findById(req.params.id);
if (!category) {
return res.status(404).json({ error: 'Categoría no encontrada' });
}
res.json({ category });
});
// Crear categoría (solo admin)
exports.createCategory = asyncHandler(async (req, res) => {
const category = await Category.create(req.body);
res.status(201).json({
message: 'Categoría creada exitosamente',
category
});
});
// Actualizar categoría (solo admin)
exports.updateCategory = asyncHandler(async (req, res) => {
const category = await Category.update(req.params.id, req.body);
if (!category) {
return res.status(404).json({ error: 'Categoría no encontrada' });
}
res.json({
message: 'Categoría actualizada exitosamente',
category
});
});
// Eliminar categoría (solo admin)
exports.deleteCategory = asyncHandler(async (req, res) => {
try {
await Category.delete(req.params.id);
res.json({ message: 'Categoría eliminada exitosamente' });
} catch (error) {
return res.status(400).json({ error: error.message });
}
});
// Obtener productos de la categoría
exports.getCategoryProducts = asyncHandler(async (req, res) => {
const { page = 1, limit = 20 } = req.query;
const offset = (page - 1) * limit;
const { products, total } = await Category.getProducts(
req.params.id,
{ limit: parseInt(limit), offset: parseInt(offset) }
);
res.json({
products,
pagination: {
currentPage: parseInt(page),
totalPages: Math.ceil(total / limit),
totalItems: total
}
});
});