forked from thomasrockhu-codecov/graphql-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl-helpers.ts
More file actions
58 lines (50 loc) · 1.51 KB
/
url-helpers.ts
File metadata and controls
58 lines (50 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Utility functions for working with URL parameters
*/
/**
* Gets a query parameter value from the current URL
* @param paramName - The name of the parameter to retrieve
* @returns The parameter value or null if not found
*/
export function getQueryParam(paramName: string): string | null {
if (typeof window === "undefined") {
return null;
}
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(paramName);
}
/**
* Gets a query parameter value and validates it against allowed values
* @param paramName - The name of the parameter to retrieve
* @param allowedValues - Array of allowed values
* @returns The parameter value if valid, or null if invalid/not found
*/
export function getValidatedQueryParam<T extends string>(
paramName: string,
allowedValues: readonly T[]
): T | null {
const value = getQueryParam(paramName);
if (value && allowedValues.includes(value as T)) {
return value as T;
}
return null;
}
/**
* Builds a URL with query parameters
* @param baseUrl - The base URL
* @param params - Object containing parameter key-value pairs
* @returns The complete URL with query parameters
*/
export function buildUrlWithParams(
baseUrl: string,
params: Record<string, string | number>
): string {
const url = new URL(
baseUrl,
typeof window !== "undefined" ? window.location.origin : ""
);
Object.entries(params).forEach(([key, value]) => {
url.searchParams.set(key, String(value));
});
return url.pathname + url.search;
}