Spaces:
Running
Running
File size: 2,305 Bytes
30a3fac | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | 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;
|