diff --git a/src/http.ts b/src/http.ts new file mode 100644 index 0000000..c8a1d66 --- /dev/null +++ b/src/http.ts @@ -0,0 +1,45 @@ +import http from 'http'; +import type { ResponseShape } from './pipeline'; + +export type RouteHandler = (req: { + method: string; url: string; + headers: Record; + params: Record; +}) => Promise; + +export interface RouteDef { method: string; pattern: string; handler: RouteHandler } +export interface MatchedRoute { params: Record; handler: RouteHandler } + +export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { + const segs = path.split('/').filter(Boolean); + for (const r of routes) { + if (r.method !== method) continue; + const pat = r.pattern.split('/').filter(Boolean); + if (pat.length !== segs.length) continue; + const params: Record = {}; + let ok = true; + for (let i = 0; i < pat.length; i++) { + if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]); + else if (pat[i] !== segs[i]) { ok = false; break; } + } + if (ok) return { params, handler: r.handler }; + } + return undefined; +} + +export function createHttpServer(routes: RouteDef[]): http.Server { + return http.createServer(async (req, res) => { + const path = (req.url ?? '/').split('?')[0]; + const matched = matchRoute(routes, req.method ?? 'GET', path); + if (!matched) { + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not Found' })); + return; + } + const result = await matched.handler({ + method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers, params: matched.params, + }); + res.writeHead(result.status, result.headers); + res.end(result.body); + }); +} diff --git a/test/http.test.ts b/test/http.test.ts new file mode 100644 index 0000000..77b1375 --- /dev/null +++ b/test/http.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from 'vitest'; +import { matchRoute } from '../src/http'; + +const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); + +test('matches a static + :param route and extracts params', () => { + const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }]; + const m = matchRoute(routes, 'GET', '/api/users/42'); + expect(m?.params).toEqual({ id: '42' }); +}); + +test('returns undefined when nothing matches', () => { + const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }]; + expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined(); + expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined(); +});