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/lib/api.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/lib/api.ts (limited to 'src/lib/api.ts') diff --git a/src/lib/api.ts b/src/lib/api.ts new file mode 100644 index 0000000..84a36c4 --- /dev/null +++ b/src/lib/api.ts @@ -0,0 +1,30 @@ +import type { APIContext } from 'astro'; + +export function jsonResponse(data: any, status: number = 200) { + return new Response(JSON.stringify(data), { + status, + headers: { 'Content-Type': 'application/json' } + }); +} + +export function getDB(locals: APIContext['locals']) { + const db = locals.runtime?.env?.DB; + if (!db) { + throw new Error('Database not available'); + } + return db; +} + +export async function handleAPIError(fn: () => Promise, fallback?: any): Promise { + try { + return await fn(); + } catch (error) { + console.error('API Error:', error); + + if (error instanceof Error && error.message === 'Database not available') { + return jsonResponse(fallback || { error: 'Database not available' }, 503); + } + + return jsonResponse({ error: 'Internal server error' }, 500); + } +} \ No newline at end of file -- cgit v1.3.1