UNPKG

2.37 kBJavaScriptView Raw
1/*! Universal Router | MIT License | https://www.kriasoft.com/universal-router/ */
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
9Router = 'default' in Router ? Router['default'] : Router;
10
11/**
12 * Universal Router (https://www.kriasoft.com/universal-router/)
13 *
14 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
15 *
16 * This source code is licensed under the Apache 2.0 license found in the
17 * LICENSE.txt file in the root directory of this source tree.
18 */
19
20/* eslint no-param-reassign: ['error', { props: false }] */
21
22var cache = new Map();
23
24function 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
42function 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 = {}; // clear cache
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
78Router.generateUrls = generateUrls;
79
80return generateUrls;
81
82})));
83//# sourceMappingURL=universal-router-generate-urls.js.map