fix: stream errors -> 500, guard non-object body picks, test @query e2e

This commit is contained in:
chrnx committed 2026-06-26 01:51:02 -05:00
1 parent 7114bf685e
commit ccaacb9a02
3 files changed
+42 -14

No files matched your search

+18 -9
View File
@@ -37,15 +37,12 @@ export function parseQuery(url: string): Record<string, string> {
return out;
}
async function readBody(req: http.IncomingMessage): Promise<unknown> {
async function readBody(req: http.IncomingMessage): Promise<string | undefined> {
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;
return raw === '' ? undefined : raw;
}
export function createHttpServer(routes: RouteDef[]): http.Server {
@@ -58,14 +55,26 @@ export function createHttpServer(routes: RouteDef[]): http.Server {
res.end(JSON.stringify({ error: 'Not Found' }));
return;
}
let body: unknown;
let raw: string | undefined;
try {
body = await readBody(req);
raw = await readBody(req);
} catch {
res.writeHead(400, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
// stream/network failure — not the client's JSON fault
res.writeHead(500, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal Server Error' }));
return;
}
let body: unknown = raw;
const ct = String(req.headers['content-type'] ?? '');
if (raw !== undefined && ct.includes('application/json')) {
try {
body = JSON.parse(raw);
} 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({
+6 -4
View File
@@ -65,12 +65,14 @@ export function resolveArgs(specs: ArgSpec[], context: Context): unknown[] {
function resolveOne(s: ArgSpec, context: Context): unknown {
if (s.source === 'ctx') return context;
if (s.source === 'needs') return context[s.key as string];
const bag = (context[s.source] ?? {}) as Record<string, unknown>;
const bag = context[s.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const record = bag as Record<string, unknown>;
if (s.keys) {
const out: Record<string, unknown> = {};
for (const k of s.keys) out[k] = bag[k];
for (const k of s.keys) out[k] = record[k];
return out;
}
if (s.key !== undefined) return bag[s.key];
return bag;
if (s.key !== undefined) return record[s.key];
return record;
}