Skip to content
This repository was archived by the owner on Mar 19, 2024. It is now read-only.

Commit 4db8565

Browse files
committed
Update routeFunction
Now we can add other parameters to the url, not only the required ones.
1 parent 09ed438 commit 4db8565

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

src/assets/js/routeFunction.js

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,36 @@
11
const route = (routeName, params = []) => {
2-
var _route = routes[routeName];
3-
if (_route == null) {
4-
throw "Requested route doesn't exist";
5-
}
2+
const _route = routes[routeName];
3+
if (_route == null) throw "Requested route doesn't exist";
64

75
var uri = _route.uri;
86

7+
const matches = uri.match(/{[\w]+}/g);
8+
const requiredParametersCount = matches.length;
9+
910
if (params instanceof Array) {
10-
params.forEach(param => {
11-
uri = uri.replace(/{[\w]+}/, param);
12-
});
11+
if (params.length < requiredParametersCount) throw "Missing parameters";
12+
13+
for (var i = 0; i < matches.length; i++)
14+
uri = uri.replace(/{[\w]+}/, params.shift());
15+
16+
for (var i = 0; i < params.length; i++)
17+
uri += (i ? "&" : "?") + params[i] + "=" + params[i];
1318
} else if (params instanceof Object) {
14-
Object.keys(params).forEach(key => {
15-
uri = uri.replace(new RegExp("{" + key + "}", "g"), params[key]);
19+
var extraParams = matches.reduce((ac, match) => {
20+
var key = match.substring(1, match.length - 1);
21+
if (params.hasOwnProperty(key)) {
22+
uri = uri.replace(new RegExp(match, "g"), params[key]);
23+
delete ac[key];
24+
}
25+
return ac;
26+
}, params);
27+
28+
Object.keys(extraParams).forEach((key, i) => {
29+
uri += (i ? "&" : "?") + key + "=" + extraParams[key];
1630
});
1731
}
1832

19-
if (uri.includes("}")) {
20-
throw "Missing parameters";
21-
}
33+
if (uri.includes("}")) throw "Missing parameters";
2234

2335
return "/" + uri;
2436
};

0 commit comments

Comments
 (0)