This commit is contained in:
Andrew 2022-02-23 02:37:30 +07:00
parent 0e2c114a84
commit 2c5995be3f
13 changed files with 632 additions and 0 deletions

54
w5/router.js Normal file
View file

@ -0,0 +1,54 @@
"use strict";
/**
*
* @param {String} method
* @param {String} path
*/
export function route(method, path) {
return `route::${method}::${path}`;
}
export class Router {
/** @type {Map.<Route, Function<http.IncomingMessage, http.ServerResponse, String, Object>>} */
routes = new Map();
/**
*
* @param {Route} route
* @param {Function.<http.IncomingMessage, http.ServerResponse, String, Object>} func
*/
addRoute(route, func) {
if (this.routes.has(route)) {
throw new Error(`Route ${route} already exists!`);
}
this.routes.set(route, func);
}
/**
*
* @param {Route} route
* @returns Function for dispatchng this route
*/
dispatch(route) {
if (this.routes.has(route)) {
return this.routes.get(route);
}
return this.returnError(404, "Not found!");
}
/**
*
* @param {Number} code
* @param {String} message
* @param {String} contentType
*/
returnError(code, message, contentType="text/plain") {
return (req, res) => {
res.setHeader("Content-Type", contentType);
res.statusCode = code;
res.write(message);
res.end();
};
}
}