export async function onRequest(context) { const { request, env } = context; const url = new URL(request.url); const path = url.pathname; // 1. יצירת הטבלאות במסד הנתונים במידה ואינן קיימות if (path === '/api/setup') { try { await env.DB.prepare(` CREATE TABLE IF NOT EXISTS machines ( id TEXT PRIMARY KEY, data TEXT ); `).run(); await env.DB.prepare(` CREATE TABLE IF NOT EXISTS products ( id TEXT PRIMARY KEY, data TEXT ); `).run(); return new Response(JSON.stringify({ success: true, message: 'DB Tables Initialized' }), { headers: { 'Content-Type': 'application/json' } }); } catch (e) { return new Response(JSON.stringify({ error: e.message }), { status: 500 }); } } // 2. ניהול מכונות (/api/machines) if (path === '/api/machines') { if (request.method === 'GET') { const { results } = await env.DB.prepare('SELECT data FROM machines').all(); const machines = results ? results.map(r => JSON.parse(r.data)) : []; return new Response(JSON.stringify(machines), { headers: { 'Content-Type': 'application/json' } }); } if (request.method === 'POST') { const machine = await request.json(); await env.DB.prepare(` INSERT INTO machines (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data `).bind(machine.id, JSON.stringify(machine)).run(); return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } }); } if (request.method === 'DELETE') { const id = url.searchParams.get('id'); await env.DB.prepare('DELETE FROM machines WHERE id = ?').bind(id).run(); return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } }); } } // 3. ניהול מוצרים (/api/products) if (path === '/api/products') { if (request.method === 'GET') { const { results } = await env.DB.prepare('SELECT data FROM products').all(); const products = results ? results.map(r => JSON.parse(r.data)) : []; return new Response(JSON.stringify(products), { headers: { 'Content-Type': 'application/json' } }); } if (request.method === 'POST') { const product = await request.json(); await env.DB.prepare(` INSERT INTO products (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data `).bind(product.id, JSON.stringify(product)).run(); return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } }); } if (request.method === 'DELETE') { const id = url.searchParams.get('id'); await env.DB.prepare('DELETE FROM products WHERE id = ?').bind(id).run(); return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' } }); } } return new Response('Not Found', { status: 404 }); }