import assert from 'node:assert/strict';
import { createServer, type IncomingMessage } from 'node:http';
import type { AddressInfo } from 'node:net';
type Item = { id: string; name: string };
type Params = Record<string, string>;
type Result = { status: number; body: unknown; headers?: Record<string, string> };
type Handler = (request: IncomingMessage, params: Params) => Result | Promise<Result>;
// A client mistake with its status code; anything else thrown is a 500.
class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const items = new Map<string, Item>([['1', { id: '1', name: 'kettle' }]]);
let nextId = 2;
// A tiny router: a method plus a pattern whose ':name' segments become params.
const routes: { method: string; pattern: string[]; handler: Handler }[] = [];
function route(method: string, pattern: string, handler: Handler): void {
routes.push({ method, pattern: pattern.split('/').filter(Boolean), handler });
}
function match(pattern: string[], pathname: string): Params | null {
const parts = pathname.split('/').filter(Boolean);
if (parts.length !== pattern.length) return null;
const params: Params = {};
for (const [i, segment] of pattern.entries()) {
if (!segment.startsWith(':')) {
if (segment !== parts[i]) return null;
} else {
try {
params[segment.slice(1)] = decodeURIComponent(parts[i]);
} catch {
throw new HttpError(400, 'malformed escape in path'); // URIError, e.g. %E0%A4%A
}
}
}
return params;
}
// Collect raw bytes (a UTF-8 character can span two chunks), cap the size, then decode.
async function readJson(request: IncomingMessage, limit = 64 * 1024): Promise<unknown> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of request) {
size += chunk.length;
if (size > limit) throw new HttpError(413, 'body too large');
chunks.push(chunk);
}
try {
// fatal: true rejects invalid UTF-8 instead of substituting U+FFFD.
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
} catch {
throw new HttpError(400, 'body must be UTF-8 JSON');
}
}
route('GET', '/items/:id', (_request, { id }) => {
const item = items.get(id);
return item ? { status: 200, body: item } : { status: 404, body: { error: 'not found' } };
});
route('POST', '/items', async (request) => {
const input = await readJson(request);
if (typeof input !== 'object' || input === null || !('name' in input) || typeof input.name !== 'string') {
return { status: 400, body: { error: 'name must be a string' } };
}
const item = { id: String(nextId++), name: input.name };
items.set(item.id, item);
return { status: 201, body: item };
});
async function dispatch(request: IncomingMessage): Promise<Result> {
// Accept only origin-form targets ("/path?query"); URL.parse returns null instead of throwing.
const target = request.url ?? '';
const url = target.startsWith('/') ? URL.parse(`http://localhost${target}`) : null;
if (url === null) throw new HttpError(400, 'bad request target');
const wanted = request.method === 'HEAD' ? 'GET' : request.method; // HEAD runs GET; Node drops the body
const allowed: string[] = [];
for (const { method, pattern, handler } of routes) {
const params = match(pattern, url.pathname);
if (params === null) continue;
if (method === wanted) return handler(request, params);
allowed.push(method === 'GET' ? 'GET, HEAD' : method);
}
if (allowed.length === 0) return { status: 404, body: { error: 'no route' } };
return { status: 405, body: { error: 'method not allowed' }, headers: { allow: allowed.join(', ') } };
}
const server = createServer(async (request, response) => {
let result: Result;
try {
result = await dispatch(request);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ECONNRESET') return; // the client went away
if (!(error instanceof HttpError)) console.error(error);
result = error instanceof HttpError
? { status: error.status, body: { error: error.message } }
: { status: 500, body: { error: 'internal error' } };
}
response.writeHead(result.status, { 'content-type': 'application/json', ...result.headers });
response.end(JSON.stringify(result.body));
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const created = await fetch(`${base}/items`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: 'mug' })
});
assert.equal(created.status, 201);
const item = (await created.json()) as Item;
assert.deepEqual(await (await fetch(`${base}/items/${item.id}`)).json(), { id: '2', name: 'mug' });
assert.equal((await fetch(`${base}/items/99`)).status, 404);
assert.equal((await fetch(`${base}/items/%E0%A4%A`)).status, 400);
assert.equal((await fetch(`${base}/items`, { method: 'POST', body: '{"name":' })).status, 400);
const wrongMethod = await fetch(`${base}/items/1`, { method: 'DELETE' });
assert.equal(wrongMethod.status, 405);
assert.equal(wrongMethod.headers.get('allow'), 'GET, HEAD');
assert.equal((await fetch(`${base}/items/1`, { method: 'HEAD' })).status, 200);
console.log('GET /items/2 ->', item);
server.close();