UNPKG

sw2express

Version:

A lite & simple cross-platform Express-like web application framework

53 lines (51 loc) 1.52 kB
import { swRequest } from "../req.js"; import { swReply } from "../rep.js"; export const makeHandler = (that) => { const page = that.DefaultPage; return async (request) => { let body = ""; if (request.method === "POST") { body = await request.text(); } let req = new swRequest(request, body), rep = new swReply(request, that.options), answer; const path = req.path; await Promise.all( that._middleWare.map((middleware) => middleware(req, rep)) ); if (!rep.isEnd) { if (that._route[path]) { if (that._route[path][request.method]) { answer = await doRequest(that._route[path][request.method], req, rep); } else if (that._route[path].all) { answer = await doRequest(that._route[path].all, req, rep); } else { answer = await doRequest(page.Code(500).GenAsync, req, rep); } } else { answer = await doRequest(page.Code(404).GenAsync, req, rep); } } else { answer = await doRequest( async (req, rep) => { "NotThingToDoHere."; }, req, rep ); } return answer; }; }; export async function doRequest(func, req, rep) { const funcAnswer = await func(req, rep).catch(async (e) => { await doRequest(page.Code(500).GenAsync, req, rep); console.log(e.stack); }); if (!rep.isEnd) { if (typeof funcAnswer !== "object") rep.end(funcAnswer); rep.json(funcAnswer); } return await rep.GenResponse(); }