61 lines
2.6 KiB
TypeScript
61 lines
2.6 KiB
TypeScript
/**
|
||
* Layers Routes – CRUD for layers
|
||
*/
|
||
import type { FastifyInstance } from 'fastify';
|
||
import type { DatabaseInterface, DBLayer } 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 registerLayerRoutes(fastify: FastifyInstance, db: DatabaseInterface, authService: AuthService) {
|
||
// List layers for a drawing
|
||
fastify.get('/api/drawings/:drawingId/layers', async (request, reply) => {
|
||
if (!requireAuth(request, reply, authService)) return;
|
||
const { drawingId } = request.params as { drawingId: string };
|
||
const idErr = validateIdParam(drawingId, 'drawingId');
|
||
if (idErr) return reply.code(400).send({ error: idErr });
|
||
return db.listLayers(drawingId);
|
||
});
|
||
|
||
// Create layer
|
||
fastify.post('/api/drawings/:drawingId/layers', async (request, reply) => {
|
||
if (!requireAuth(request, reply, authService)) return;
|
||
const { drawingId } = request.params as { drawingId: string };
|
||
const idErr = validateIdParam(drawingId, 'drawingId');
|
||
if (idErr) return reply.code(400).send({ error: idErr });
|
||
const body = request.body as Partial<DBLayer>;
|
||
if (body.name !== undefined) {
|
||
const nameErr = validateName(body.name);
|
||
if (nameErr) return reply.code(400).send({ error: nameErr });
|
||
}
|
||
return reply.code(201).send(db.createLayer({ ...body, drawing_id: drawingId }));
|
||
});
|
||
|
||
// Update layer
|
||
fastify.patch('/api/layers/: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<DBLayer>;
|
||
if (body.name !== undefined) {
|
||
const nameErr = validateName(body.name);
|
||
if (nameErr) return reply.code(400).send({ error: nameErr });
|
||
}
|
||
const updated = db.updateLayer(id, body);
|
||
if (!updated) return reply.code(404).send({ error: 'Layer not found' });
|
||
return updated;
|
||
});
|
||
|
||
// Delete layer
|
||
fastify.delete('/api/layers/: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.deleteLayer(id);
|
||
if (!ok) return reply.code(404).send({ error: 'Layer not found' });
|
||
return reply.code(204).send();
|
||
});
|
||
}
|