import { serve, serveTls } from "https://deno.land/std@0.140.0/http/server.ts";import { Router } from "./router.ts";import { Req, Res, Routes } from "./types.ts";
class WebApp { public routes: Routes[] = []; private dHeaders: Record<string, string> = {}; private allowME = false;
private hand404 = (_: Req, res: Res): void => { res.reply = JSON.stringify({ status: 404, massage: "Route Not Found", }); res.headers = { "Content-Type": "application/json", }; };
private hand500 = (_: Req, res: Res): void => { res.reply = JSON.stringify({ status: 500, massage: "Internal Server Error", }); res.headers = { "Content-Type": "application/json", }; };
public headers = (headers: Record<string, string>) => this.dHeaders = headers;
public allowMoreExp = (allow: boolean) => this.allowME = allow;
public set = async (r: Router) => { this.routes = await r.getRoutes(this.allowME); };
public set404 = (hand: (req: Req, res: Res) => void) => { this.hand404 = hand; };
public set500 = (hand: (req: Req, res: Res) => void) => { this.hand500 = hand; };
private hand = async (req: Request): Promise<Response> => { const url = new URL(req.url);
let is404 = true;
const res: Res = { reply: "", headers: {}, status: 200, };
const r: Req = { state: {} };
for (const ele of this.routes) { if ( url.pathname.match(ele.reg) && (ele.method === req.method || ele.method === "ALL") ) { is404 = false;
if (req.body) { r.body = await req.text(); }
r.headers = req.headers; r.method = req.method; r.url = url; r.reg = ele.reg;
try { for (const h of ele.hand) { await h(r, res); if (await res.reply !== "") { break; } } } catch (_e) { await this.hand500(r, res); } break; } }
if (is404) { if (req.body) { r.body = await req.text(); } r.headers = req.headers; r.method = req.method; r.url = url; try { await this.hand404(r, res); } catch (_e) { await this.hand500(r, res); } }
return new Response( typeof res.reply !== "object" ? res.reply : JSON.stringify(res.reply), { status: res.status, headers: { ...this.dHeaders, ...res.headers }, }, ); };
public listen = (port: number) => { serve(this.hand, { port: port, }); };
public listenTls = (port: number, certFile: string, keyFile: string) => { serveTls(this.hand, { port: port, certFile, keyFile, }); };}
export { WebApp };