From 5bb825e29334455119f8da746b69d644fb6539a8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 26 Jun 2026 01:42:01 -0500 Subject: [PATCH] feat: parse query string and json body into the request --- src/http.ts | 36 +++++++++++++++++++++++++++++++++--- test/http.test.ts | 28 +++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/src/http.ts b/src/http.ts index 7196135..3eccf1c 100644 --- a/src/http.ts +++ b/src/http.ts @@ -1,11 +1,13 @@ import http from 'http'; -import type { ResponseShape } from './pipeline'; import { errorToResponse } from './transformers'; +import type { ResponseShape } from './pipeline'; export type RouteHandler = (req: { method: string; url: string; headers: Record; params: Record; + query: Record; + body: unknown; }) => Promise; export interface RouteDef { method: string; pattern: string; handler: RouteHandler } @@ -28,19 +30,47 @@ export function matchRoute(routes: RouteDef[], method: string, path: string): Ma return undefined; } +export function parseQuery(url: string): Record { + const qs = url.split('?')[1] ?? ''; + const out: Record = {}; + for (const [k, v] of new URLSearchParams(qs)) out[k] = v; + return out; +} + +async function readBody(req: http.IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + if (chunks.length === 0) return undefined; + const raw = Buffer.concat(chunks).toString('utf8'); + if (!raw) return undefined; + const ct = String(req.headers['content-type'] ?? ''); + if (ct.includes('application/json')) return JSON.parse(raw); // throws → caller maps to 400 + return raw; +} + export function createHttpServer(routes: RouteDef[]): http.Server { return http.createServer(async (req, res) => { - const path = (req.url ?? '/').split('?')[0]; + const url = req.url ?? '/'; + const path = 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; } + let body: unknown; + try { + body = await readBody(req); + } catch { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid JSON body' })); + return; + } let result: ResponseShape; try { result = await matched.handler({ - method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers, params: matched.params, + method: req.method ?? 'GET', url, headers: req.headers, + params: matched.params, query: parseQuery(url), body, }); } catch (error) { result = errorToResponse(error); diff --git a/test/http.test.ts b/test/http.test.ts index 77b1375..4a451bd 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import { matchRoute } from '../src/http'; +import { matchRoute, parseQuery, createHttpServer } from '../src/http'; const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); @@ -14,3 +14,29 @@ test('returns undefined when nothing matches', () => { expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined(); expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined(); }); + +test('parseQuery extracts query params from a url', () => { + expect(parseQuery('/api/users/9?q=hi&date=2026')).toEqual({ q: 'hi', date: '2026' }); + expect(parseQuery('/api/users/9')).toEqual({}); +}); + +test('server parses json body and rejects malformed json with 400', async () => { + const server = createHttpServer([{ + method: 'POST', pattern: '/echo', + handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body, q: req.query }) }), + }]); + await new Promise((r) => server.listen(0, r)); + const port = (server.address() as any).port; + + const ok = await fetch(`http://127.0.0.1:${port}/echo?x=1`, { + method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ a: 1 }), + }); + expect(await ok.json()).toEqual({ got: { a: 1 }, q: { x: '1' } }); + + const bad = await fetch(`http://127.0.0.1:${port}/echo`, { + method: 'POST', headers: { 'content-type': 'application/json' }, body: '{not json', + }); + expect(bad.status).toBe(400); + + server.close(); +});