|
1 | | -export function route<T extends string>( |
2 | | - path: T, |
3 | | - params?: Record<string, any> |
4 | | -): T { |
5 | | - if (params) { |
6 | | - const segments = path.split(/\/+/).map((segment) => { |
7 | | - if (segment.startsWith(":")) { |
8 | | - const key = segment.replace(":", "").replace("?", ""); |
9 | | - |
10 | | - if (key in params) { |
11 | | - return params[key]; |
12 | | - } |
| 1 | +export function route<T extends string>(path: T, params: Record<string, any> = {}): T { |
| 2 | + if (!path.includes('?') && !path.includes(':')) { |
| 3 | + return path; |
| 4 | + } |
13 | 5 |
|
14 | | - // If the segment is optional and it doesn't exist in params, return null to omit it from the resulting path |
15 | | - if (segment.endsWith("?")) { |
16 | | - return null; |
17 | | - } |
18 | | - } |
| 6 | + let realPath = ""; |
| 7 | + let currentIndex = path.length; |
| 8 | + let lastSegmentHadParam = false; |
19 | 9 |
|
20 | | - return segment; |
21 | | - }); |
| 10 | + while (currentIndex > 0) { |
| 11 | + const startSegmentIndex = path.lastIndexOf('/', currentIndex); |
| 12 | + const segment = path.slice(startSegmentIndex, currentIndex + 1); |
| 13 | + currentIndex = startSegmentIndex - 1; |
22 | 14 |
|
23 | | - // Filter out any null/undefined segments and join remaining segments |
24 | | - return segments.filter((value) => value != null).join("/") as T; |
| 15 | + if (segment.startsWith('/:')) { |
| 16 | + const paramName = segment.endsWith('?') ? segment.slice(2, -1) : segment.slice(2); |
| 17 | + const paramValue = params[paramName]; |
| 18 | + if (paramValue !== undefined) { |
| 19 | + lastSegmentHadParam = true; |
| 20 | + realPath = '/' + paramValue + realPath; |
| 21 | + } |
| 22 | + } else if (segment.endsWith('?')) { |
| 23 | + if (lastSegmentHadParam) { |
| 24 | + realPath = segment.slice(0, -1) + realPath; |
| 25 | + } |
| 26 | + } else { |
| 27 | + lastSegmentHadParam = false; |
| 28 | + realPath = segment + realPath; |
| 29 | + } |
25 | 30 | } |
26 | 31 |
|
27 | | - return path; |
| 32 | + return realPath as T; |
28 | 33 | } |
0 commit comments