src/index.mjs gelöscht
This commit is contained in:
		
							
								
								
									
										139
									
								
								src/index.mjs
									
									
									
									
									
								
							
							
						
						
									
										139
									
								
								src/index.mjs
									
									
									
									
									
								
							@@ -1,139 +0,0 @@
 | 
			
		||||
import http from "http";
 | 
			
		||||
import { URL } from "url";
 | 
			
		||||
import { Buffer } from "buffer";
 | 
			
		||||
import querystring from "querystring";
 | 
			
		||||
 | 
			
		||||
import Router from "./router.mjs";
 | 
			
		||||
import Tpl from "./template.mjs";
 | 
			
		||||
 | 
			
		||||
export { Router, Tpl };
 | 
			
		||||
 | 
			
		||||
export default class flummpress {
 | 
			
		||||
  #server;
 | 
			
		||||
 | 
			
		||||
  constructor() {
 | 
			
		||||
    this.router = new Router();
 | 
			
		||||
    this.tpl = new Tpl();
 | 
			
		||||
    this.middleware = new Set();
 | 
			
		||||
    return this;
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  use(obj) {
 | 
			
		||||
    if(obj instanceof Router) {
 | 
			
		||||
      this.router.use(obj);
 | 
			
		||||
    }
 | 
			
		||||
    else if(obj instanceof Tpl) {
 | 
			
		||||
      this.tpl = obj;
 | 
			
		||||
    }
 | 
			
		||||
    else {
 | 
			
		||||
      if(!this.middleware.has(obj))
 | 
			
		||||
        this.middleware.add(obj);
 | 
			
		||||
    }
 | 
			
		||||
    return this;
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  listen(...args) {
 | 
			
		||||
    this.#server = http.createServer(async (req, res) => {
 | 
			
		||||
      const t_start = process.hrtime();
 | 
			
		||||
 | 
			
		||||
      const _url = new URL(req.url.replace(/(?!^.)(\/+)?$/, ''), "relative:///");
 | 
			
		||||
      req.url = {
 | 
			
		||||
        pathname: _url.pathname,
 | 
			
		||||
        split: _url.pathname.split("/").slice(1),
 | 
			
		||||
        searchParams: _url.searchParams,
 | 
			
		||||
        qs: {...querystring.parse(_url.search.substring(1))} // legacy
 | 
			
		||||
      };
 | 
			
		||||
 | 
			
		||||
      req.cookies = {};
 | 
			
		||||
      if(req.headers.cookie) {
 | 
			
		||||
        req.headers.cookie.split("; ").forEach(c => {
 | 
			
		||||
          const parts = c.split('=');
 | 
			
		||||
          req.cookies[parts.shift().trim()] = decodeURI(parts.join('='));
 | 
			
		||||
        });
 | 
			
		||||
      }
 | 
			
		||||
 | 
			
		||||
      await Promise.all([...this.middleware].map(m => m(req, res)));
 | 
			
		||||
 | 
			
		||||
      const method = req.method === 'HEAD' ? 'get' : req.method.toLowerCase();
 | 
			
		||||
      const route = this.router.getRoute(req.url.pathname, req.method == 'HEAD' ? 'GET' : req.method);
 | 
			
		||||
 | 
			
		||||
      if(route) { // 200
 | 
			
		||||
        const cb = route[1][method];
 | 
			
		||||
        const middleware = route[1][`${method}mw`];
 | 
			
		||||
        req.params = req.url.pathname.match(new RegExp(route[0]))?.groups;
 | 
			
		||||
        req.post = await this.readBody(req);
 | 
			
		||||
 | 
			
		||||
        const result = await this.processMiddleware(middleware, req, this.createResponse(res));
 | 
			
		||||
        if(result)
 | 
			
		||||
          cb(req, res);
 | 
			
		||||
      }
 | 
			
		||||
      else { // 404
 | 
			
		||||
        res
 | 
			
		||||
          .writeHead(404)
 | 
			
		||||
          .end(`404 - ${req.method} ${req.url.pathname}`);
 | 
			
		||||
      }
 | 
			
		||||
 | 
			
		||||
      console.log([
 | 
			
		||||
        `[${(new Date()).toLocaleTimeString()}]`,
 | 
			
		||||
        `${(process.hrtime(t_start)[1] / 1e6).toFixed(2)}ms`,
 | 
			
		||||
        `${req.method} ${res.statusCode}`,
 | 
			
		||||
        req.url.pathname
 | 
			
		||||
      ].map(e => e.toString().padEnd(15)).join(""));
 | 
			
		||||
 | 
			
		||||
    }).listen(...args);
 | 
			
		||||
    return this;
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  readBody(req) {
 | 
			
		||||
    return new Promise((resolve, _, data = "") => req
 | 
			
		||||
      .on("data", d => void (data += d))
 | 
			
		||||
      .on("end", () => {
 | 
			
		||||
        if(req.headers['content-type'] === "application/json") {
 | 
			
		||||
          try {
 | 
			
		||||
            return void resolve(JSON.parse(data));
 | 
			
		||||
          } catch(err) {}
 | 
			
		||||
        }
 | 
			
		||||
        void resolve(Object.fromEntries(Object.entries(querystring.parse(data)).map(([k, v]) => {
 | 
			
		||||
          try {
 | 
			
		||||
            return [k, decodeURIComponent(v)];
 | 
			
		||||
          } catch(err) {
 | 
			
		||||
            return [k, v];
 | 
			
		||||
          }
 | 
			
		||||
        })));
 | 
			
		||||
      }));
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  createResponse(res) {
 | 
			
		||||
    res.reply = ({
 | 
			
		||||
      code = 200,
 | 
			
		||||
      type = "text/html",
 | 
			
		||||
      body
 | 
			
		||||
    }) => {
 | 
			
		||||
      res.writeHead(code, {
 | 
			
		||||
        "content-type": `${type}; charset=UTF-8`,
 | 
			
		||||
        "content-length": Buffer.byteLength(body, 'utf-8')
 | 
			
		||||
      });
 | 
			
		||||
      if(res.method === 'HEAD')
 | 
			
		||||
        body = null;
 | 
			
		||||
      res.end(body);
 | 
			
		||||
      return res;
 | 
			
		||||
    };
 | 
			
		||||
    res.json = (body, code = 200) => {
 | 
			
		||||
      if(typeof body === 'object')
 | 
			
		||||
        body = JSON.stringify(body);
 | 
			
		||||
      return res.reply({ code, body, type: "application/json" });
 | 
			
		||||
    };
 | 
			
		||||
    res.html = (body, code = 200) => res.reply({ code, body, type: "text/html" });
 | 
			
		||||
    res.redirect = (target, code = 307) => res.writeHead(code, {
 | 
			
		||||
      "Cache-Control": "no-cache, public",
 | 
			
		||||
      "Location": target
 | 
			
		||||
    }).end();
 | 
			
		||||
    return res;
 | 
			
		||||
  };
 | 
			
		||||
 | 
			
		||||
  processMiddleware(middleware, req, res) {
 | 
			
		||||
    if(!middleware)
 | 
			
		||||
      return new Promise(resolve => resolve(true));
 | 
			
		||||
    return new Promise(resolve => middleware(req, res, () => resolve(true)));
 | 
			
		||||
  };
 | 
			
		||||
};
 | 
			
		||||
		Reference in New Issue
	
	Block a user