summaryrefslogtreecommitdiff
path: root/src/lib/api.ts
diff options
context:
space:
mode:
authorYuval Adam <_@yuv.al>2025-06-27 13:14:00 +0200
committerYuval Adam <_@yuv.al>2025-06-27 13:14:00 +0200
commit72b63296438f469fc261562690495580ab8547d9 (patch)
tree5d6e7ed36b7c59b1371f0de3f7711496d2086348 /src/lib/api.ts
parentbc750614c5780ff1f3e59d692492924ffe70edd6 (diff)
Extract common api stuffastro-base-cf
Diffstat (limited to 'src/lib/api.ts')
-rw-r--r--src/lib/api.ts30
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