45 lines
1.4 KiB
JavaScript
45 lines
1.4 KiB
JavaScript
// src/router/pattern-router/router.ts
|
|
import { METHOD_NAME_ALL, UnsupportedPathError } from "../../router.js";
|
|
var PatternRouter = class {
|
|
name = "PatternRouter";
|
|
routes = [];
|
|
add(method, path, handler) {
|
|
const endsWithWildcard = path[path.length - 1] === "*";
|
|
if (endsWithWildcard) {
|
|
path = path.slice(0, -2);
|
|
}
|
|
if (path.at(-1) === "?") {
|
|
path = path.slice(0, -1);
|
|
this.add(method, path.replace(/\/[^/]+$/, ""), handler);
|
|
}
|
|
const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map(
|
|
(part) => {
|
|
const match = part.match(/^\/:([^{]+)(?:{(.*)})?/);
|
|
return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&");
|
|
}
|
|
);
|
|
let re;
|
|
try {
|
|
re = new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`);
|
|
} catch (e) {
|
|
throw new UnsupportedPathError();
|
|
}
|
|
this.routes.push([re, method, handler]);
|
|
}
|
|
match(method, path) {
|
|
const handlers = [];
|
|
for (const [pattern, routeMethod, handler] of this.routes) {
|
|
if (routeMethod === METHOD_NAME_ALL || routeMethod === method) {
|
|
const match = pattern.exec(path);
|
|
if (match) {
|
|
handlers.push([handler, match.groups || /* @__PURE__ */ Object.create(null)]);
|
|
}
|
|
}
|
|
}
|
|
return [handlers];
|
|
}
|
|
};
|
|
export {
|
|
PatternRouter
|
|
};
|