Files
web-cad/backend/src/routes/projects.ts
T

66 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<DBProject>;
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<DBProject>;
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();
});
}