1+ import Log from '@libs/Log' ;
12import Navigation from '@libs/Navigation/Navigation' ;
23import type { Route } from '@src/ROUTES' ;
3- import combineDynamicRoutePathAndSuffix from './combineDynamicRoutePathAndSuffix' ;
44import isDynamicRouteSuffix from './isDynamicRouteSuffix' ;
55import splitPathAndQuery from './splitPathAndQuery' ;
66
7+ /**
8+ * Merges two query strings into one. If both contain the same key, an error is thrown.
9+ */
10+ const mergeQueryStrings = ( baseQuery = '' , suffixQuery = '' ) : string => {
11+ if ( ! baseQuery && ! suffixQuery ) {
12+ return '' ;
13+ }
14+ const params = new URLSearchParams ( baseQuery ) ;
15+ const suffixParams = new URLSearchParams ( suffixQuery ) ;
16+ for ( const [ key , value ] of suffixParams . entries ( ) ) {
17+ if ( params . has ( key ) ) {
18+ throw new Error ( `[createDynamicRoute] Query param "${ key } " exists in both base path and dynamic suffix. This is not allowed.` ) ;
19+ }
20+ params . set ( key , value ) ;
21+ }
22+ const result = params . toString ( ) ;
23+ return result ? `?${ result } ` : '' ;
24+ } ;
25+
726/** Adds dynamic route name (with optional query params) to the current URL and returns it */
827const createDynamicRoute = ( dynamicRouteSuffixWithParams : string , basePath ?: string ) : Route => {
928 const [ suffixPath ] = splitPathAndQuery ( dynamicRouteSuffixWithParams ) ;
@@ -13,6 +32,17 @@ const createDynamicRoute = (dynamicRouteSuffixWithParams: string, basePath?: str
1332 }
1433
1534 const routePath = basePath ?? Navigation . getActiveRoute ( ) ;
16- return combineDynamicRoutePathAndSuffix ( routePath , dynamicRouteSuffixWithParams ) ;
35+ const [ normalizedBasePath , baseQuery ] = splitPathAndQuery ( routePath ) ;
36+ const [ normalizedSuffixPath , suffixQuery ] = splitPathAndQuery ( dynamicRouteSuffixWithParams ) ;
37+
38+ if ( ! normalizedBasePath ) {
39+ Log . warn ( '[createDynamicRoute.ts] Path is undefined or empty, returning suffix only' , { basePath : routePath , suffixWithQuery : dynamicRouteSuffixWithParams } ) ;
40+ return dynamicRouteSuffixWithParams as Route ;
41+ }
42+
43+ const combinedPath = normalizedBasePath === '/' ? `/${ normalizedSuffixPath } ` : `${ normalizedBasePath } /${ normalizedSuffixPath } ` ;
44+ const mergedQuery = mergeQueryStrings ( baseQuery , suffixQuery ) ;
45+
46+ return `${ combinedPath } ${ mergedQuery } ` as Route ;
1747} ;
1848export default createDynamicRoute ;
0 commit comments