This commit is contained in:
@ -1,17 +1,37 @@
|
||||
const routes = [];
|
||||
let currentCleanup = null;
|
||||
|
||||
/** @returns {{ regex: RegExp, paramNames: string[] }} */
|
||||
export function compileRoute(pattern) {
|
||||
const paramNames = [];
|
||||
const parts = pattern.replace(/\/:([^/]+)/g, (_, name) => {
|
||||
paramNames.push(name);
|
||||
return '/([^/]+)';
|
||||
});
|
||||
return { regex: new RegExp('^' + parts + '$'), paramNames };
|
||||
}
|
||||
|
||||
/** Match a path against a string route pattern; returns params or null. */
|
||||
export function matchRoute(pattern, path) {
|
||||
const { regex, paramNames } = compileRoute(pattern);
|
||||
const match = path.match(regex);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const params = {};
|
||||
paramNames.forEach((name, i) => {
|
||||
params[name] = decodeURIComponent(match[i + 1]);
|
||||
});
|
||||
return params;
|
||||
}
|
||||
|
||||
export function addRoute(pattern, handler) {
|
||||
let regex;
|
||||
const paramNames = [];
|
||||
let paramNames = [];
|
||||
if (pattern instanceof RegExp) {
|
||||
regex = pattern;
|
||||
} else {
|
||||
const parts = pattern.replace(/\/:([^/]+)/g, (_, name) => {
|
||||
paramNames.push(name);
|
||||
return '/([^/]+)';
|
||||
});
|
||||
regex = new RegExp('^' + parts + '$');
|
||||
({ regex, paramNames } = compileRoute(pattern));
|
||||
}
|
||||
routes.push({ regex, paramNames, handler });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user