feat: parse query string and json body into the request
This commit is contained in:
2 files changed
+60
-4
No files matched your search
+33
-3
@@ -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<string, string | string[] | undefined>;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
}) => Promise<ResponseShape>;
|
||||
|
||||
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<string, string> {
|
||||
const qs = url.split('?')[1] ?? '';
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of new URLSearchParams(qs)) out[k] = v;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function readBody(req: http.IncomingMessage): Promise<unknown> {
|
||||
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);
|
||||
|
||||
+27
-1
@@ -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<void>((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();
|
||||
});
|
||||
Reference in new issue
Block a user