@@ -4,23 +4,28 @@ const route = (routeName, params = [], absolute = true) => {
4
4
5
5
let uri = _route . uri ;
6
6
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 ;
9
11
10
12
if ( params instanceof Array ) {
11
13
if ( params . length < requiredParametersCount ) throw "Missing parameters" ;
12
14
13
15
for ( let i = 0 ; i < requiredParametersCount ; i ++ )
14
- uri = uri . replace ( / { [ \w ] + } / , params . shift ( ) ) ;
16
+ uri = uri . replace ( / { [ \w ] + \? ? } / , params . shift ( ) ) ;
15
17
16
18
for ( let i = 0 ; i < params . length ; i ++ )
17
19
uri += ( i ? "&" : "?" ) + params [ i ] + "=" + params [ i ] ;
18
20
} else if ( params instanceof Object ) {
19
21
let extraParams = matches . reduce ( ( ac , match ) => {
20
22
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" ) , "" ) ;
24
29
}
25
30
return ac ;
26
31
} , params ) ;
@@ -30,6 +35,12 @@ const route = (routeName, params = [], absolute = true) => {
30
35
} ) ;
31
36
}
32
37
38
+ if ( optionals . length > 0 ) {
39
+ for ( let i in optionals ) {
40
+ uri = uri . replace ( "/" + optionals [ i ] , "" ) ;
41
+ }
42
+ }
43
+
33
44
if ( uri . includes ( "}" ) ) throw "Missing parameters" ;
34
45
35
46
if ( absolute && process . env . MIX_APP_URL )
0 commit comments