|
| 1 | +import type { DiscoveredDatabase } from "../database.ts"; |
| 2 | +import type { ApiResponse, RouteContext, DatabaseConstructor } from "./types.ts"; |
| 3 | +import { matchRoute } from "./router.ts"; |
| 4 | +import { routes } from "../routes/index.ts"; |
| 5 | +import { errorResponse } from "./responses.ts"; |
| 6 | + |
| 7 | +/** |
| 8 | + * Handle API requests using Node.js primitives |
| 9 | + */ |
| 10 | +export async function handleApiRequest( |
| 11 | + url: string, |
| 12 | + method: string, |
| 13 | + body: string, |
| 14 | + databases: DiscoveredDatabase[], |
| 15 | + Database: DatabaseConstructor |
| 16 | +): Promise<ApiResponse> { |
| 17 | + // Parse URL path (remove query string if present) |
| 18 | + const path = url.split('?')[0]; |
| 19 | + |
| 20 | + try { |
| 21 | + // Try to match against registered routes |
| 22 | + const context: RouteContext = { databases, Database }; |
| 23 | + |
| 24 | + for (const route of routes) { |
| 25 | + if (route.method !== method) continue; |
| 26 | + |
| 27 | + const params = matchRoute(route.pattern, path); |
| 28 | + if (params) { |
| 29 | + return await route.handler(params, context, body); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // No route matched - return 404 |
| 34 | + return { status: 404, headers: {}, body: '' }; |
| 35 | + |
| 36 | + } catch (err) { |
| 37 | + const errorMessage = err instanceof Error ? err.message : "Unknown error"; |
| 38 | + console.error("Error handling request:", err); |
| 39 | + return errorResponse(errorMessage, 500); |
| 40 | + } |
| 41 | +} |
| 42 | + |
0 commit comments