add fetcher logic to makeRequest

This commit is contained in:
Jorrin
2024-01-09 23:35:56 +01:00
parent f669b2d168
commit 441d1cb617
2 changed files with 35 additions and 7 deletions

24
src/utils/fetcher.ts Normal file
View File

@@ -0,0 +1,24 @@
import { type Request as MakeRequest } from '~background/messages/makeRequest';
export function makeFullUrl(url: string, ops?: MakeRequest): string {
// glue baseUrl and rest of url together
let leftSide = ops?.baseUrl ?? '';
let rightSide = url;
// left side should always end with slash, if its set
if (leftSide.length > 0 && !leftSide.endsWith('/')) leftSide += '/';
// right side should never start with slash
if (rightSide.startsWith('/')) rightSide = rightSide.slice(1);
const fullUrl = leftSide + rightSide;
if (!fullUrl.startsWith('http://') && !fullUrl.startsWith('https://'))
throw new Error(`Invald URL -- URL doesn't start with a http scheme: '${fullUrl}'`);
const parsedUrl = new URL(fullUrl);
Object.entries(ops?.query ?? {}).forEach(([k, v]) => {
parsedUrl.searchParams.set(k, v);
});
return parsedUrl.toString();
}