"use strict"; /** * * @param {String} method * @param {String} path */ export function route(method, path) { return `route::${method}::${path}`; } export class Router { /** @type {Map.>} */ routes = new Map(); /** * * @param {Route} route * @param {Function.} 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(); }; } }