refactor: extract business logic from routes into reusable service modules

This commit is contained in:
Maurice
2026-04-02 17:14:53 +02:00
parent f0131632a7
commit 979322025d
48 changed files with 8851 additions and 6182 deletions
+10 -31
View File
@@ -1,55 +1,34 @@
import express, { Request, Response } from 'express';
import { db } from '../db/database';
import { authenticate, adminOnly } from '../middleware/auth';
import { AuthRequest } from '../types';
import * as categoryService from '../services/categoryService';
const router = express.Router();
router.get('/', authenticate, (_req: Request, res: Response) => {
const categories = db.prepare(
'SELECT * FROM categories ORDER BY name ASC'
).all();
res.json({ categories });
res.json({ categories: categoryService.listCategories() });
});
router.post('/', authenticate, adminOnly, (req: Request, res: Response) => {
const authReq = req as AuthRequest;
const { name, color, icon } = req.body;
if (!name) return res.status(400).json({ error: 'Category name is required' });
const result = db.prepare(
'INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)'
).run(name, color || '#6366f1', icon || '\uD83D\uDCCD', authReq.user.id);
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(result.lastInsertRowid);
const category = categoryService.createCategory(authReq.user.id, name, color, icon);
res.status(201).json({ category });
});
router.put('/:id', authenticate, adminOnly, (req: Request, res: Response) => {
const { name, color, icon } = req.body;
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(req.params.id);
if (!category) return res.status(404).json({ error: 'Category not found' });
db.prepare(`
UPDATE categories SET
name = COALESCE(?, name),
color = COALESCE(?, color),
icon = COALESCE(?, icon)
WHERE id = ?
`).run(name || null, color || null, icon || null, req.params.id);
const updated = db.prepare('SELECT * FROM categories WHERE id = ?').get(req.params.id);
res.json({ category: updated });
if (!categoryService.getCategoryById(req.params.id))
return res.status(404).json({ error: 'Category not found' });
const category = categoryService.updateCategory(req.params.id, name, color, icon);
res.json({ category });
});
router.delete('/:id', authenticate, adminOnly, (req: Request, res: Response) => {
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(req.params.id);
if (!category) return res.status(404).json({ error: 'Category not found' });
db.prepare('DELETE FROM categories WHERE id = ?').run(req.params.id);
if (!categoryService.getCategoryById(req.params.id))
return res.status(404).json({ error: 'Category not found' });
categoryService.deleteCategory(req.params.id);
res.json({ success: true });
});