Routing
by evgkch
JavaScript
const KnowledgeBase = 'KnowledgeBase';
const Home = 'Home';
const Result = 'Result';
const List = 'List';
const Article = 'Article';
let router = {
path: 'knowledge',
component: KnowledgeBase,
indexLink: 'home',
childRoutes: [
{
path: 'home',
component: Home
},
{
path: 'result',
component: Result,
},
{
path: 'article',
component: Article,
indexLink: ':article',
childRoutes: [
{
path: ':article',
component: Article,
},
{
path: 'view',
component: Article,
}
]
}
]
}
const splitPath = (path) => path.split('/').filter(x => x !== '');
const iteratePath = (splitPath, index = 0) => () => splitPath[index++];
const findPathIndex = (childRoutes) => (path) => {
let index;
childRoutes.map((child, i) =>
(child.path === path) ? index = i : -1
)
return index;
};
const updateRoute = (thisPath, nextPath, router) => {
thisPath = nextPath();
if (!!router.indexLink && !!router.childRoutes) {
let index = findPathIndex(router.childRoutes)(thisPath);
if (index !== undefined) {
if (router.indexLink !== thisPath) {
router.indexLink = thisPath;
}
updateRoute(thisPath, nextPath, router.childRoutes[index])
} else {
console.error(`"${router.path}" container does not contain "${thisPath}" link in router.childRoutes. Check the link or router`)
}
}
}
class App {
constructor(router) {
this.router = router;
}
redirect(path) {
let newPath = iteratePath(splitPath(path)),
thisPath = newPath();
updateRoute(thisPath, newPath, this.router);
}
}
const app = new App(router);
app.redirect('/knowledge/home')
console.log(app)
app.redirect('/knowledge/article/:article')
console.log(app)