From 72b63296438f469fc261562690495580ab8547d9 Mon Sep 17 00:00:00 2001 From: Yuval Adam <_@yuv.al> Date: Fri, 27 Jun 2025 13:14:00 +0200 Subject: Extract common api stuff --- src/pages/api/tasks.ts | 58 +++++++++----------------------------------------- 1 file changed, 10 insertions(+), 48 deletions(-) (limited to 'src/pages/api/tasks.ts') diff --git a/src/pages/api/tasks.ts b/src/pages/api/tasks.ts index 8784e97..2b76ed3 100644 --- a/src/pages/api/tasks.ts +++ b/src/pages/api/tasks.ts @@ -1,68 +1,30 @@ import type { APIRoute } from 'astro'; +import { jsonResponse, getDB, handleAPIError } from '../../lib/api'; export const prerender = false; export const GET: APIRoute = async ({ locals }) => { - try { - const db = locals.runtime?.env?.DB; - - if (!db) { - console.error('Database not available'); - return new Response(JSON.stringify([]), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }); - } - + return handleAPIError(async () => { + const db = getDB(locals); const { results } = await db.prepare('SELECT * FROM tasks ORDER BY created_at DESC').all(); - - return new Response(JSON.stringify(results || []), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }); - } catch (error) { - console.error('Database error:', error); - return new Response(JSON.stringify([]), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }); - } + return jsonResponse(results || []); + }, []); }; export const POST: APIRoute = async ({ request, locals }) => { - try { - const db = locals.runtime?.env?.DB; - - if (!db) { - return new Response(JSON.stringify({ error: 'Database not available' }), { - status: 503, - headers: { 'Content-Type': 'application/json' } - }); - } - + return handleAPIError(async () => { + const db = getDB(locals); const body = await request.json(); const { title, description } = body; if (!title) { - return new Response(JSON.stringify({ error: 'Title is required' }), { - status: 400, - headers: { 'Content-Type': 'application/json' } - }); + return jsonResponse({ error: 'Title is required' }, 400); } const { results } = await db.prepare( 'INSERT INTO tasks (title, description) VALUES (?, ?) RETURNING *' ).bind(title, description || '').all(); - return new Response(JSON.stringify(results?.[0] || { id: Date.now(), title, description, completed: false }), { - status: 201, - headers: { 'Content-Type': 'application/json' } - }); - } catch (error) { - console.error('Database error:', error); - return new Response(JSON.stringify({ error: 'Failed to create task' }), { - status: 500, - headers: { 'Content-Type': 'application/json' } - }); - } + return jsonResponse(results?.[0] || { id: Date.now(), title, description, completed: false }, 201); + }); }; \ No newline at end of file -- cgit v1.3.1