sozday-dlya-menya-prilozheni/server.js

53 lines
3.2 KiB
JavaScript

/* Сервер без зависимостей: статика + API погоды и актуальной афиши. */
const http = require("http");
const fs = require("fs");
const path = require("path");
const {getEnvironment} = require("./environment");
const {getEvents,chooseEvening,dateKey,activeEvents,SOURCE} = require("./events");
const PORT = process.env.PORT || 3000;
const MIME = {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf"};
function sendJson(res,status,data) {
res.writeHead(status,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"});
res.end(JSON.stringify(data));
}
async function api(req,res,pathname,query) {
if (pathname === "/api/health") return sendJson(res,200,{ok:true});
if (pathname === "/api/environment") {
const result = await getEnvironment();
return sendJson(res,200,{...result.data,stale:result.stale});
}
if (pathname === "/api/events") {
try {
const result = await getEvents();
return sendJson(res,200,{events:result.events,active:activeEvents(result.events,dateKey()),source:SOURCE,fetchedAt:result.fetchedAt,live:result.live,stale:result.stale});
} catch (error) {
return sendJson(res,200,{events:[],active:[],source:SOURCE,live:false,error:"Афиша временно недоступна"});
}
}
if (pathname === "/api/evening") {
const date = /^\d{4}-\d{2}-\d{2}$/.test(query.get("date")||"") ? query.get("date") : dateKey();
const [eventsResult,weatherResult] = await Promise.allSettled([getEvents(),getEnvironment()]);
const events = eventsResult.status === "fulfilled" ? eventsResult.value.events : [];
const weather = weatherResult.status === "fulfilled" ? weatherResult.value.data : {temp:10,feels:10,aqi:null,wind:0};
const idea = chooseEvening(events,weather,date);
return sendJson(res,200,{...idea,events,eventsLive:eventsResult.status === "fulfilled" && eventsResult.value.live,weatherLive:weatherResult.status === "fulfilled"});
}
return sendJson(res,404,{error:"API не найден"});
}
http.createServer(async (req,res)=>{
const pathname = req.url.split("?")[0];
if (pathname.startsWith("/api/")) {
try { return await api(req,res,pathname,new URL(req.url,"http://localhost").searchParams); }
catch (error) { console.error("API",pathname,error.message); return sendJson(res,503,{error:"Сервис временно недоступен"}); }
}
let file;
try { file = decodeURIComponent(pathname === "/" ? "/index.html" : pathname); } catch (_) { res.writeHead(400); return res.end("Bad request"); }
const full = path.resolve(__dirname,"."+file);
if (full.startsWith(__dirname+path.sep) && fs.existsSync(full) && fs.statSync(full).isFile()) {
res.writeHead(200,{"Content-Type":(MIME[path.extname(full)]||"application/octet-stream")+"; charset=utf-8"});
return res.end(fs.readFileSync(full));
}
res.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"});
res.end("Not found");
}).listen(PORT,()=>console.log("Ауада запущена на порту "+PORT));