diff options
| author | Yuval Adam <_@yuv.al> | 2025-06-27 13:14:00 +0200 |
|---|---|---|
| committer | Yuval Adam <_@yuv.al> | 2025-06-27 13:14:00 +0200 |
| commit | 72b63296438f469fc261562690495580ab8547d9 (patch) | |
| tree | 5d6e7ed36b7c59b1371f0de3f7711496d2086348 /src/lib/api.ts | |
| parent | bc750614c5780ff1f3e59d692492924ffe70edd6 (diff) | |
Extract common api stuffastro-base-cf
Diffstat (limited to 'src/lib/api.ts')
| -rw-r--r-- | src/lib/api.ts | 30 |
1 files changed, 30 insertions, 0 deletions
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<Response>, fallback?: any): Promise<Response> { + 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 |
