dika/src/index.js

85 lines
4.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { buildList, findAddress } from "./lib.js";
import { createStore, checkPassword } from "./admin.js";
import { renderPage } from "./page.js";
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
const types = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" };
// dataDir — где лежит живая база (по умолчанию data/ рядом с кодом), password — пароль владельца базы.
export function createHandler({ dataDir = path.join(root, "data"), seedDir = path.join(root, "data"), password = "" } = {}) {
const store = createStore(dataDir, seedDir);
return (req, res) => handle(req, res, store, password);
}
const defaultHandler = () => createHandler({
dataDir: process.env.DATA_DIR || path.join(root, "data"), password: process.env.ADMIN_PASSWORD || "",
});
function admin(req, res, url, store, password, json) {
if (!password) {
res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
return res.end("Правка отключена: не задан пароль владельца базы. Задайте пароль и откройте страницу снова.");
}
if (!checkPassword(req.headers.authorization, password)) {
res.writeHead(401, { "www-authenticate": 'Basic realm="admin", charset="UTF-8"', "content-type": "text/plain; charset=utf-8" });
return res.end("Нужен пароль");
}
if (url.pathname === "/admin" && req.method === "GET") {
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
return res.end(fs.readFileSync(path.join(root, "admin", "index.html")));
}
if (url.pathname === "/admin/api/venues" && req.method === "GET") return json(200, store.list());
const m = /^\/admin\/api\/venues\/([\w-]+)$/.exec(url.pathname);
if (m && req.method === "POST") {
let body = "";
req.on("data", (c) => { body += c; if (body.length > 20000) req.destroy(); });
req.on("end", () => {
let patch;
try { patch = JSON.parse(body); } catch { return json(400, { error: "bad_request" }); }
const r = store.update(m[1], patch || {});
return json(r.ok ? 200 : r.error === "not_found" ? 404 : 400, r);
});
return;
}
return json(404, { error: "not_found" });
}
function handle(req, res, store, password) {
const db = store.db;
const url = new URL(req.url, "http://x");
const json = (code, body) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
if (url.pathname === "/admin" || url.pathname.startsWith("/admin/")) return admin(req, res, url, store, password, json);
if (url.pathname === "/healthz") return json(200, { ok: true });
if (url.pathname === "/api/base") return json(200, store.all());
if (url.pathname === "/api/districts") return json(200, db.districts.map((d) => ({ ...d, count: db.venues.filter((v) => v.district === d.name).length })));
if (url.pathname === "/api/locate") {
const v = findAddress(db.venues, url.searchParams.get("q") || "");
return v ? json(200, { lat: v.lat, lng: v.lng }) : json(404, { error: "not_found" });
}
if (url.pathname === "/api/venues") {
const lat = Number(url.searchParams.get("lat")), lng = Number(url.searchParams.get("lng"));
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return json(400, { error: "bad_coords" });
return json(200, buildList(db.venues, lat, lng, { only: url.searchParams.get("only") === "1" }));
}
const rel = url.pathname === "/" ? "index.html" : url.pathname === "/base" ? "base.html" : url.pathname.slice(1);
const file = path.normalize(path.join(root, "public", rel));
if (!file.startsWith(path.join(root, "public")) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.writeHead(404); return res.end("Not found");
}
res.writeHead(200, { "content-type": types[path.extname(file)] || "application/octet-stream" });
if (path.extname(file) === ".html") {
// страница уходит сразу с русскими текстами — подписи есть и без скрипта
const ru = JSON.parse(fs.readFileSync(path.join(root, "public", "i18n", "ru.json"), "utf8"));
return res.end(renderPage(fs.readFileSync(file, "utf8"), ru));
}
fs.createReadStream(file).pipe(res);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
http.createServer(defaultHandler()).listen(Number(process.env.PORT) || 3000);
}