71 lines
2.0 KiB
JavaScript
71 lines
2.0 KiB
JavaScript
class Router {
|
|
constructor(base) {
|
|
this.routes = [];
|
|
this.base = base;
|
|
};
|
|
|
|
addRoute(method, path, handler) {
|
|
const paramNames = [];
|
|
const regexPath = path
|
|
.replace(/:([^/]+)/g, (match, paramName) => {
|
|
paramNames.push(paramName);
|
|
return '([^/]+)';
|
|
})
|
|
.replace(/\*/g, '.*');
|
|
|
|
this.routes.push({
|
|
method,
|
|
path,
|
|
regex: new RegExp(`^${regexPath}$`),
|
|
paramNames,
|
|
handler
|
|
});
|
|
}
|
|
|
|
get(path, handler) {
|
|
this.addRoute("GET", this.base ? this.base + path : path, handler);
|
|
console.info(this.base ? this.base + path : path)
|
|
}
|
|
|
|
post(path, handler) {
|
|
this.addRoute("POST", this.base ? this.base + path : path, handler);
|
|
console.info("POST", this.base ? this.base + path : path)
|
|
|
|
}
|
|
|
|
put(path, handler) {
|
|
this.addRoute("PUT", this.base ? this.base + path : path, handler);
|
|
}
|
|
|
|
delete(path, handler) {
|
|
this.addRoute("DELETE", this.base ? this.base + path : path, handler);
|
|
}
|
|
|
|
handle(res, req) {
|
|
const method = req.getMethod().toUpperCase();
|
|
const urlPrepare = req.getUrl().split("/");
|
|
const urlRelevant = urlPrepare.slice(2, urlPrepare.length);
|
|
const url = "/" + urlRelevant.join("/");
|
|
console.info("hm?", method)
|
|
for (const route of this.routes) {
|
|
if (route.method === method) {
|
|
const match = url.match(route.regex);
|
|
console.info(url, route, method)
|
|
if (!match) continue;
|
|
|
|
const params = {};
|
|
route.paramNames.forEach((name, index) => params[name] = match[index + 1]);
|
|
|
|
req.params = params;
|
|
|
|
return route.handler(res, req);
|
|
};
|
|
};
|
|
|
|
res
|
|
.writeStatus("404 Not Found")
|
|
.end("Invalid route");
|
|
}
|
|
};
|
|
|
|
module.exports = Router; |