from microdot import Microdot from models.pallet import Palette import json controller = Microdot() palettes = Palette() @controller.get('') async def list_palettes(request): """List all palettes.""" data = {} for pid in palettes.list(): colors = palettes.read(pid) data[pid] = colors return json.dumps(data), 200, {'Content-Type': 'application/json'} @controller.get('/') async def get_palette(request, id): """Get a specific palette by ID.""" palette = palettes.read(id) if palette: return json.dumps({"colors": palette, "id": str(id)}), 200, {'Content-Type': 'application/json'} return json.dumps({"error": "Palette not found"}), 404 @controller.post('') async def create_palette(request): """Create a new palette.""" try: data = request.json or {} colors = data.get("colors", None) # Palette no longer needs a name; only colors are stored. palette_id = palettes.create("", colors) palette = palettes.read(palette_id) or {} # Include the ID in the response payload so clients can link it. palette_with_id = {"id": str(palette_id)} palette_with_id.update(palette) return json.dumps(palette_with_id), 201, {'Content-Type': 'application/json'} except Exception as e: return json.dumps({"error": str(e)}), 400 @controller.put('/') async def update_palette(request, id): """Update an existing palette.""" try: data = request.json or {} # Ignore any name field; only colors are relevant. if "name" in data: data.pop("name", None) if palettes.update(id, data): palette = palettes.read(id) or {} palette_with_id = {"id": str(id)} palette_with_id.update(palette) return json.dumps(palette_with_id), 200, {'Content-Type': 'application/json'} return json.dumps({"error": "Palette not found"}), 404 except Exception as e: return json.dumps({"error": str(e)}), 400 @controller.delete('/') async def delete_palette(request, id): """Delete a palette.""" if palettes.delete(id): return json.dumps({"message": "Palette deleted successfully"}), 200 return json.dumps({"error": "Palette not found"}), 404