UNPKG

@itrocks/route

Version:

Domain-driven route manager with automatic generation, decorators, and static routes

91 lines 2.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Routes = void 0; const path_1 = require("path"); const destination_1 = require("./destination"); const destination_2 = require("./destination"); class Routes { routes = {}; add(path, destination) { let route = this.routes; const names = path.split(path_1.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 ((0, destination_1.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 ((0, destination_1.isDestination)(position)) { return position; } const step = position[name]; if (step) { position = step; } } if ((typeof position === 'object') && position['.']) { position = position['.']; } return (0, destination_1.isDestination)(position) ? position : undefined; } resolve(route) { const destination = this.destination(route); if (!destination) { return undefined; } return (0, destination_2.resolveDestination)(destination); } simplify() { function simplifyStep(step, parentStep, parentName) { if ((0, destination_1.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 ((0, destination_1.isDestination)(position)) { return summary; } const step = position[name]; if (step) { summary += '/' + name; position = step; } } if ((typeof position === 'object') && position['.']) { position = position['.']; } return summary; } } exports.Routes = Routes; //# sourceMappingURL=routes.js.map