1 |
|
2 |
|
3 | (function (global, factory) {
|
4 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./universal-router.js')) :
|
5 | typeof define === 'function' && define.amd ? define(['./universal-router.js'], factory) :
|
6 | (global.generateUrls = factory(global.UniversalRouter));
|
7 | }(this, (function (Router) { 'use strict';
|
8 |
|
9 | Router = 'default' in Router ? Router['default'] : Router;
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | var cache = new Map();
|
23 |
|
24 | function cacheRoutes(routesByName, route, routes) {
|
25 | if (routesByName[route.name]) {
|
26 | throw new Error('Route "' + route.name + '" already exists');
|
27 | }
|
28 |
|
29 | if (route.name) {
|
30 | routesByName[route.name] = route;
|
31 | }
|
32 |
|
33 | if (routes) {
|
34 | for (var i = 0; i < routes.length; i += 1) {
|
35 | var childRoute = routes[i];
|
36 | childRoute.parent = route;
|
37 | cacheRoutes(routesByName, childRoute, childRoute.children);
|
38 | }
|
39 | }
|
40 | }
|
41 |
|
42 | function generateUrls(router, options) {
|
43 | if (!(router instanceof Router)) {
|
44 | throw new TypeError('An instance of Router is expected');
|
45 | }
|
46 |
|
47 | router.routesByName = router.routesByName || {};
|
48 |
|
49 | return function (routeName, params) {
|
50 | var route = router.routesByName[routeName];
|
51 | if (!route) {
|
52 | router.routesByName = {};
|
53 | cacheRoutes(router.routesByName, router.root, router.root.children);
|
54 |
|
55 | route = router.routesByName[routeName];
|
56 | if (!route) {
|
57 | throw new Error('Route "' + routeName + '" not found');
|
58 | }
|
59 | }
|
60 |
|
61 | var path = '';
|
62 | while (route) {
|
63 | if (route.path !== '/') {
|
64 | var toPath = cache.get(route.path);
|
65 | if (!toPath) {
|
66 | toPath = Router.pathToRegexp.compile(route.path);
|
67 | cache.set(route.path, toPath);
|
68 | }
|
69 | path = toPath(params, options) + path;
|
70 | }
|
71 | route = route.parent;
|
72 | }
|
73 |
|
74 | return router.baseUrl + path || '/';
|
75 | };
|
76 | }
|
77 |
|
78 | Router.generateUrls = generateUrls;
|
79 |
|
80 | return generateUrls;
|
81 |
|
82 | })));
|
83 |
|