-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
32c50bb
commit 59aaf78
Showing
2 changed files
with
46 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,33 @@ | ||
export function route<T extends string>( | ||
path: T, | ||
params?: Record<string, any> | ||
): T { | ||
if (params) { | ||
const segments = path.split(/\/+/).map((segment) => { | ||
if (segment.startsWith(":")) { | ||
const key = segment.replace(":", "").replace("?", ""); | ||
|
||
if (key in params) { | ||
return params[key]; | ||
} | ||
export function route<T extends string>(path: T, params: Record<string, any> = {}): T { | ||
if (!path.includes('?') && !path.includes(':')) { | ||
return path; | ||
} | ||
|
||
// If the segment is optional and it doesn't exist in params, return null to omit it from the resulting path | ||
if (segment.endsWith("?")) { | ||
return null; | ||
} | ||
} | ||
let realPath = ""; | ||
let currentIndex = path.length; | ||
let lastSegmentHadParam = false; | ||
|
||
return segment; | ||
}); | ||
while (currentIndex > 0) { | ||
const startSegmentIndex = path.lastIndexOf('/', currentIndex); | ||
const segment = path.slice(startSegmentIndex, currentIndex + 1); | ||
currentIndex = startSegmentIndex - 1; | ||
|
||
// Filter out any null/undefined segments and join remaining segments | ||
return segments.filter((value) => value != null).join("/") as T; | ||
if (segment.startsWith('/:')) { | ||
const paramName = segment.endsWith('?') ? segment.slice(2, -1) : segment.slice(2); | ||
const paramValue = params[paramName]; | ||
if (paramValue !== undefined) { | ||
lastSegmentHadParam = true; | ||
realPath = `/${paramValue}` + realPath; | ||
} | ||
} else if (segment.endsWith('?')) { | ||
if (lastSegmentHadParam) { | ||
realPath = segment.slice(0, -1) + realPath; | ||
} | ||
} else { | ||
lastSegmentHadParam = false; | ||
realPath = segment + realPath; | ||
} | ||
} | ||
|
||
return path; | ||
} | ||
return realPath as T; | ||
} |