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

Commit e8134dc

Browse files
authored
Merge pull request #6 from geodro/patch-1
add support for optional {param?}
2 parents 52b117e + a35b500 commit e8134dc

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/assets/js/routeFunction.js

+17-6
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,28 @@ const route = (routeName, params = [], absolute = true) => {
44

55
let uri = _route.uri;
66

7-
const matches = uri.match(/{[\w]+}/g) || [];
8-
const requiredParametersCount = matches.length;
7+
const matches = uri.match(/{[\w]+\??}/g) || [];
8+
const optionals = uri.match(/{[\w]+\?}/g) || [];
9+
10+
const requiredParametersCount = matches.length - optionals.length;
911

1012
if (params instanceof Array) {
1113
if (params.length < requiredParametersCount) throw "Missing parameters";
1214

1315
for (let i = 0; i < requiredParametersCount; i++)
14-
uri = uri.replace(/{[\w]+}/, params.shift());
16+
uri = uri.replace(/{[\w]+\??}/, params.shift());
1517

1618
for (let i = 0; i < params.length; i++)
1719
uri += (i ? "&" : "?") + params[i] + "=" + params[i];
1820
} else if (params instanceof Object) {
1921
let extraParams = matches.reduce((ac, match) => {
2022
let 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];
23+
let isOptional = key.endsWith("?");
24+
if (params.hasOwnProperty(key.replace("?", ""))) {
25+
uri = uri.replace(new RegExp(match.replace("?", "\\?"), "g"), params[key.replace("?", "")]);
26+
delete ac[key.replace("?", "")];
27+
} else if (isOptional) {
28+
uri = uri.replace("/" + new RegExp(match, "g"), "");
2429
}
2530
return ac;
2631
}, params);
@@ -30,6 +35,12 @@ const route = (routeName, params = [], absolute = true) => {
3035
});
3136
}
3237

38+
if (optionals.length > 0) {
39+
for (let i in optionals) {
40+
uri = uri.replace("/" + optionals[i], "");
41+
}
42+
}
43+
3344
if (uri.includes("}")) throw "Missing parameters";
3445

3546
if (absolute && process.env.MIX_APP_URL)

0 commit comments

Comments
 (0)