sw2express
Version:
A lite & simple cross-platform Express-like web application framework
99 lines (94 loc) • 2.41 kB
JavaScript
import * as node from "./src/node/node.js";
//import * as sw from "./sw/sw.js";
import * as sw from "./src/sw/sw.js";
import toMD5 from "./src/utils/toMD5.js";
import registerPlugins from "./Plugins/register.js";
import * as page from "./src/HTTPPage/page.js";
export function checkPlatform() {
if (!(typeof process === "undefined")) {
return "NODE";
} else if (!(typeof self === "undefined")) {
return "SW";
} else {
return "UNKNOWN";
}
}
class sw2express {
constructor(options = { logger: false, ETag: true, cluster: false }) {
this.options = {
logger: options.logger,
ETag: options.ETag,
cluster: options.cluster,
};
this._route = {};
this._middleWare = [];
this.DefaultPage = page;
globalThis.platform = checkPlatform();
globalThis.md5 = toMD5();
}
use(MiddleWare) {
this._middleWare.push(MiddleWare);
return this;
}
route(url) {
this._route[url] = {};
const that = {
POST: (func) => {
this._route[url].POST = func;
return that;
},
GET: (func) => {
this._route[url].GET = func;
return that;
},
all: (func) => {
this._route[url].all = func;
return that;
},
};
return that;
}
makeNewHandler(platform) {
switch (platform) {
case "NODE": {
return {
listen: (port) => node.newHTTPServer(port).then((e) => e(this)),
Server: () => node.newHTTPServer().then((e) => e(this)),
Handler: node.HTTPHandler(this),
};
}
case "SW": {
return sw.makeHandler(this);
}
case "VERCEL": {
return node.HTTPHandler(this);
}
default:
return new Error("Invalid Platform");
}
}
listen(port) {
switch (checkPlatform()) {
case "NODE": {
let answer = "NODE",
Handler = this.makeNewHandler(answer);
Handler.listen(port);
return Handler;
}
case "SW": {
let answer = "SW",
Handler = this.makeNewHandler(answer);
self.addEventListener("fetch", (event) =>
event.respondWith(Handler(event.request))
);
return Handler;
}
}
}
extend({ name, func, bootstrap }) {
this[name] = func(this);
return bootstrap(this);
}
}
export default sw2express;
export const plugins = { register: registerPlugins };