/** * Projects Routes – CRUD for projects */ import type { FastifyInstance } from 'fastify'; import type { DatabaseInterface, DBProject } from '../database/DatabaseInterface.js'; import { requireAuth } from '../auth/authMiddleware.js'; import type { AuthService } from '../auth/AuthService.js'; import { validateName, validateIdParam } from '../utils/validation.js'; export function registerProjectRoutes(fastify: FastifyInstance, db: DatabaseInterface, authService: AuthService) { // List projects owned by the authenticated user fastify.get('/api/projects', async (request, reply) => { const user = requireAuth(request, reply, authService); if (!user) return; return db.listProjects(user.id); }); // Get single project fastify.get('/api/projects/:id', async (request, reply) => { if (!requireAuth(request, reply, authService)) return; const { id } = request.params as { id: string }; const idErr = validateIdParam(id, 'id'); if (idErr) return reply.code(400).send({ error: idErr }); const project = db.getProject(id); if (!project) return reply.code(404).send({ error: 'Project not found' }); return project; }); // Create project fastify.post('/api/projects', async (request, reply) => { const user = requireAuth(request, reply, authService); if (!user) return; const body = request.body as Partial; const nameErr = validateName(body.name); if (nameErr) return reply.code(400).send({ error: nameErr }); return reply.code(201).send(db.createProject({ ...body, owner_id: user.id })); }); // Update project fastify.patch('/api/projects/:id', async (request, reply) => { if (!requireAuth(request, reply, authService)) return; const { id } = request.params as { id: string }; const idErr = validateIdParam(id, 'id'); if (idErr) return reply.code(400).send({ error: idErr }); const body = request.body as Partial; if (body.name !== undefined) { const nameErr = validateName(body.name); if (nameErr) return reply.code(400).send({ error: nameErr }); } const updated = db.updateProject(id, body); if (!updated) return reply.code(404).send({ error: 'Project not found' }); return updated; }); // Delete project fastify.delete('/api/projects/:id', async (request, reply) => { if (!requireAuth(request, reply, authService)) return; const { id } = request.params as { id: string }; const idErr = validateIdParam(id, 'id'); if (idErr) return reply.code(400).send({ error: idErr }); const ok = db.deleteProject(id); if (!ok) return reply.code(404).send({ error: 'Project not found' }); return reply.code(204).send(); }); }