convert-route
Version:
Convert between rou3, Next.js, and path-to-regexp route patterns
54 lines (52 loc) • 1.52 kB
JavaScript
import { SegmentMapper } from "./utils/mapper.js";
import { ConvertRouteError } from "./utils/error.js";
import { join } from "./utils/join.js";
//#region src/adapters/path-to-regexp-v6.ts
const mapper = new SegmentMapper().match(/^\(\.\*\)$/, () => ({
optional: true,
catchAll: { greedy: true }
})).match(/^\(\.\+\)$/, () => ({ catchAll: { greedy: true } })).match(/\(.*\)/, () => {
throw new ConvertRouteError("[path-to-regexp-v6] Custom matching patterns are not supported");
}).match(/\{.*}/, () => {
throw new ConvertRouteError("[path-to-regexp-v6] Custom prefix and suffix are not supported");
}).match(/^:(.+)\?$/, (match) => ({
optional: true,
catchAll: {
name: match[1],
greedy: false
}
})).match(/^:(.+)\*$/, (match) => ({
optional: true,
catchAll: {
name: match[1],
greedy: true
}
})).match(/^:(.+)\+$/, (match) => ({ catchAll: {
name: match[1],
greedy: true
} })).match(/^:(.+)$/, (match) => ({ catchAll: {
name: match[1],
greedy: false
} }));
function fromPathToRegexpV6(path) {
return {
pattern: path,
params: mapper.exec(path)
};
}
function toPathToRegexpV6(route) {
let i = 0;
return join(route.params.map((r) => {
if (r.catchAll?.greedy) {
const name = r.catchAll.name || `_${++i}`;
return r.optional ? `:${name}*` : `:${name}+`;
}
if (r.catchAll && !r.catchAll.greedy) {
const name = r.catchAll.name || `_${++i}`;
return r.optional ? `:${name}?` : `:${name}`;
}
return r.value;
}))[0];
}
//#endregion
export { fromPathToRegexpV6, toPathToRegexpV6 };