W5 done
This commit is contained in:
parent
0e2c114a84
commit
2c5995be3f
13 changed files with 632 additions and 0 deletions
54
w5/router.js
Normal file
54
w5/router.js
Normal 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();
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue