You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.3 KiB
40 lines
1.3 KiB
import type { HttpSearchInit } from './types';
|
|
|
|
export function normalizeSearch(input: HttpSearchInit | undefined): URLSearchParams | undefined {
|
|
if (input === undefined) return undefined;
|
|
|
|
if (input instanceof URLSearchParams) return new URLSearchParams(input);
|
|
|
|
if (typeof input === 'string') {
|
|
return new URLSearchParams(input.startsWith('?') ? input.slice(1) : input);
|
|
}
|
|
|
|
const out = new URLSearchParams();
|
|
|
|
if (Array.isArray(input)) {
|
|
for (const [key, value] of input) out.append(key, String(value));
|
|
return out;
|
|
}
|
|
|
|
for (const [key, value] of Object.entries(input)) {
|
|
if (value === null || value === undefined) continue;
|
|
out.append(key, String(value));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export function appendSearch(url: string, params: URLSearchParams | undefined): string {
|
|
if (params === undefined || params.size === 0) return url;
|
|
const separator = url.includes('?') ? '&' : '?';
|
|
return `${url}${separator}${params.toString()}`;
|
|
}
|
|
|
|
export function resolveUrl(url: string, baseUrl: string | undefined): string {
|
|
if (baseUrl === undefined || baseUrl === '') return url;
|
|
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url)) return url;
|
|
|
|
const trimmedBase = baseUrl.split('?')[0].split('#')[0].replace(/\/+$/, '');
|
|
const trimmedUrl = url.replace(/^\/+/, '');
|
|
return `${trimmedBase}/${trimmedUrl}`;
|
|
}
|