import { Router } from 'express'; import { supabase } from '../supabase.js'; const router = Router(); const TABLE = 'zprojects'; // List all projects router.get('/', async (req, res) => { const { data, error } = await supabase .from(TABLE) .select('*') .order('id', { ascending: true }); if (error) return res.status(500).json({ error: error.message }); res.json(data); }); // Get one project router.get('/:id', async (req, res) => { const { data, error } = await supabase .from(TABLE) .select('*') .eq('id', req.params.id) .single(); if (error) return res.status(404).json({ error: error.message }); res.json(data); }); // Create project router.post('/', async (req, res) => { const { name, note, struc } = req.body; if (!name) return res.status(400).json({ error: 'name is required' }); const payload = { name, note: note ?? null, struc: normalizeStruc(struc) }; const { data, error } = await supabase .from(TABLE) .insert(payload) .select() .single(); if (error) return res.status(500).json({ error: error.message }); res.status(201).json(data); }); // Update project router.put('/:id', async (req, res) => { const { name, note, struc } = req.body; const payload = {}; if (name !== undefined) payload.name = name; if (note !== undefined) payload.note = note; if (struc !== undefined) payload.struc = normalizeStruc(struc); const { data, error } = await supabase .from(TABLE) .update(payload) .eq('id', req.params.id) .select() .single(); if (error) return res.status(500).json({ error: error.message }); res.json(data); }); // Delete project router.delete('/:id', async (req, res) => { const { error } = await supabase.from(TABLE).delete().eq('id', req.params.id); if (error) return res.status(500).json({ error: error.message }); res.status(204).end(); }); // struc may arrive as a JSON string from a textarea; store it as an object. function normalizeStruc(struc) { if (struc === undefined || struc === null || struc === '') return {}; if (typeof struc === 'object') return struc; try { return JSON.parse(struc); } catch { // Keep raw text under a key rather than failing the request. return { raw: String(struc) }; } } export default router;