UNPKG

xmt-base

Version:

Backend Server Framework of XmT Inc.

98 lines 4.04 kB
"use strict"; const http_1 = require("http"); const url_1 = require("url"); const serveStatic = require("serve-static"); const interface_1 = require("./interface"); class Router { constructor() { this.xmt_serialList = []; this.xmt_mountPath = ""; this.xmt_absolutePath = ""; this.xmt_mount = (path, router) => { if (typeof path !== "string" || path === "" || path === "/" || path[0] !== '/' || (path.length > 1 && path[path.length - 1] === '/')) { throw new Error("Router.xmt_mount() requires non-'/', '/'-begin and non-end-'/' path"); } if (!(router instanceof Router)) { throw new Error("Router.xmt_mount() requires a Router"); } for (let storedItem of this.xmt_serialList) { if (storedItem instanceof Router) { if (path === storedItem.xmt_mountPath) { throw new Error("Router already on: " + path); } } } router.xmt_mountPath = path; this.xmt_serialList.push(router); }; this.xmt_addTask = (httpMethod, task) => { if (typeof task !== "function") { throw new Error("Router.xmt_" + httpMethod + "() requires callable task function"); } let taskItem = task.bind(null); taskItem.xmt_httpMethod = httpMethod; this.xmt_serialList.push(taskItem); }; this.xmt_all = (task) => { this.xmt_addTask("all", task); }; this.xmt_get = (task) => { this.xmt_addTask("get", task); }; this.xmt_post = (task) => { this.xmt_addTask("post", task); }; this.xmt_put = (task) => { this.xmt_addTask("put", task); }; this.xmt_delete = (task) => { this.xmt_addTask("delete", task); }; this.xmt_common = (task) => { this.xmt_addTask("common", task); }; this.xmt_recurseSetAbsolutePath = (absolutePathPrefix) => { Router.recurseSetAbsolutePathCounter++; if (absolutePathPrefix === "root") { this.xmt_absolutePath = "/"; this.xmt_mountPath = "root"; } else { if (absolutePathPrefix === "/") { this.xmt_absolutePath = this.xmt_mountPath; } else { this.xmt_absolutePath = absolutePathPrefix + this.xmt_mountPath; } } for (let StoredItem of this.xmt_serialList) { if (StoredItem instanceof Router) { StoredItem.xmt_recurseSetAbsolutePath(this.xmt_absolutePath); } } }; this.xmt_listen = (port, done) => { if (typeof port !== "number") { throw new Error("Router.xmt_listen() requires a number port"); } this.xmt_recurseSetAbsolutePath("root"); return http_1.createServer(this.incomingRequestHandler).listen(port, done); }; this.incomingRequestHandler = (request, response) => { request.xmt_originalURL = request.url; request.xmt_parsedURL = url_1.parse(request.url, true); request.xmt_response = response; response.xmt_request = request; Object.assign(request, interface_1.requestProto); Object.assign(response, interface_1.responseProto); request.xmt_taskList = []; interface_1.buildRunList(this, request, request.xmt_taskList); interface_1.schedule(request.xmt_taskList, request, response); }; } } exports.Router = Router; Router.serveStatic = serveStatic; Router.recurseSetAbsolutePathCounter = 0; //# sourceMappingURL=router.js.map