You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
7 years ago
|
export type RouteKeysType = { [Identifier: string]: any };
|
||
|
|
||
|
export class RouteResolver {
|
||
|
routes: {};
|
||
|
|
||
|
constructor(routes: {}) {
|
||
|
this.routes = routes;
|
||
|
}
|
||
|
|
||
|
getRoute(name: string, _keys?: RouteKeysType): string {
|
||
|
let dict = this.routes;
|
||
|
|
||
|
let path: string[] = [];
|
||
|
name.split('.').forEach((key) => {
|
||
|
const val = (typeof dict[key] === 'string') ? dict[key] : dict[key]._base;
|
||
|
path.push(val);
|
||
|
|
||
|
dict = dict[key];
|
||
|
});
|
||
|
|
||
|
if (_keys) {
|
||
|
let keys = Object.assign({}, _keys);
|
||
|
|
||
|
path = path.map((pathComponent) => {
|
||
|
return pathComponent.split('/').map((val) => {
|
||
|
if (val[0] === ':') {
|
||
|
const ret = keys[val.slice(1)];
|
||
|
if (ret === undefined) {
|
||
|
throw new Error('Missing key: ' + val.slice(1));
|
||
|
}
|
||
|
|
||
|
delete keys[val.slice(1)];
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
return val;
|
||
|
}).join('/');
|
||
|
});
|
||
|
|
||
|
if (Object.keys(keys).length !== 0) {
|
||
|
throw new Error('Too many keys for route.');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return '/' + path.join('/');
|
||
|
}
|
||
|
}
|