54 lines
No EOL
1.3 KiB
JavaScript
54 lines
No EOL
1.3 KiB
JavaScript
"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();
|
|
};
|
|
}
|
|
} |