@itrocks/route
Version:
Domain-driven route manager with automatic generation, decorators, and static routes
87 lines • 2.71 kB
JavaScript
import { sep } from 'path';
import { isDestination } from './destination.js';
import { resolveDestination } from './destination.js';
export class Routes {
routes = {};
add(path, destination) {
let route = this.routes;
const names = path.split(sep).slice(1).reverse();
const length = names.length - 1;
for (let index = 0; index < length; index++) {
const name = names[index];
let step = route[name] ?? {};
if (isDestination(step)) {
step = { '.': step };
}
route = route[name] = step;
}
const name = names[length];
if (route[name]) {
Object.assign(route[name], { '.': destination });
}
else {
route[name] = destination;
}
}
destination(route) {
let position = this.routes;
for (const name of route.slice(1).split('/').reverse()) {
if (isDestination(position)) {
return position;
}
const step = position[name];
if (step) {
position = step;
}
}
if ((typeof position === 'object') && position['.']) {
position = position['.'];
}
return isDestination(position)
? position
: undefined;
}
resolve(route) {
const destination = this.destination(route);
if (!destination) {
return undefined;
}
return resolveDestination(destination);
}
simplify() {
function simplifyStep(step, parentStep, parentName) {
if (isDestination(step)) {
return;
}
for (const [name, nextStep] of Object.entries(step)) {
simplifyStep(nextStep, step, name);
}
const steps = Object.values(step);
if (steps.length === 1) {
parentStep[parentName] = steps[0];
}
}
for (const [name, step] of Object.entries(this.routes)) {
simplifyStep(step, this.routes, name);
}
}
summarize(route) {
let position = this.routes;
let summary = '';
for (const name of route.slice(1).split('/').reverse()) {
if (isDestination(position)) {
return summary;
}
const step = position[name];
if (step) {
summary += '/' + name;
position = step;
}
}
if ((typeof position === 'object') && position['.']) {
position = position['.'];
}
return summary;
}
}
//# sourceMappingURL=routes.js.map