70 lines
2.3 KiB
JavaScript
70 lines
2.3 KiB
JavaScript
// Маленький роутер и помощники ответа. Маршрут: { method, path: "/api/items/:id", handler(ctx) }.
|
|
// ctx = { req, res, params, query, body() }.
|
|
|
|
export function match(pattern, pathname) {
|
|
const a = pattern.split("/").filter(Boolean);
|
|
const b = pathname.split("/").filter(Boolean);
|
|
if (a.length !== b.length) return null;
|
|
const params = {};
|
|
for (let i = 0; i < a.length; i++) {
|
|
if (a[i].startsWith(":")) params[a[i].slice(1)] = decodeURIComponent(b[i]);
|
|
else if (a[i] !== b[i]) return null;
|
|
}
|
|
return params;
|
|
}
|
|
|
|
export async function handle(routes, req, res) {
|
|
const url = new URL(req.url ?? "/", "http://local");
|
|
for (const r of routes) {
|
|
if (r.method !== req.method) continue;
|
|
const params = match(r.path, url.pathname);
|
|
if (!params) continue;
|
|
await r.handler({ req, res, params, query: Object.fromEntries(url.searchParams), body: () => readBody(req) });
|
|
return;
|
|
}
|
|
html(res, page("Страница не найдена", "<h1>Страница не найдена</h1>"), 404);
|
|
}
|
|
|
|
export async function readBody(req) {
|
|
const chunks = [];
|
|
for await (const c of req) chunks.push(c);
|
|
const raw = Buffer.concat(chunks).toString("utf8");
|
|
if (!raw) return {};
|
|
const type = String(req.headers["content-type"] ?? "");
|
|
if (type.includes("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(raw));
|
|
try {
|
|
return JSON.parse(raw);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
export function json(res, status, body) {
|
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
res.end(JSON.stringify(body));
|
|
}
|
|
|
|
export function html(res, body, status = 200) {
|
|
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
res.end(body);
|
|
}
|
|
|
|
export function esc(s) {
|
|
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
}
|
|
|
|
export function page(title, body) {
|
|
return `<!doctype html>
|
|
<html lang="ru">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>${esc(title)}</title>
|
|
<style>body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;line-height:1.5}</style>
|
|
</head>
|
|
<body>
|
|
${body}
|
|
</body>
|
|
</html>`;
|
|
}
|