Skip to content

Commit

Permalink
refactor(resolveUrl): decouple from $URL (#186)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
DaniAcu and pi0 authored Feb 5, 2024
1 parent c39b9e9 commit 3b66d62
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 13 deletions.
47 changes: 42 additions & 5 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,51 @@ export function normalizeURL(input: string): string {
return createURL(input).toString();
}

export function resolveURL(base: string, ...input: string[]): string {
const url = createURL(base);
export function resolveURL(base = "", ...inputs: string[]): string {
if (typeof base !== "string") {
throw new TypeError(
`URL input should be string received ${typeof base} (${base})`
);
}

const filteredInputs = inputs.filter((input) => isNonEmptyURL(input));

if (filteredInputs.length === 0) {
return base;
}

const url = parseURL(base);

for (const inputSegment of filteredInputs) {
const urlSegment = parseURL(inputSegment);

for (const index of input.filter((url) => isNonEmptyURL(url))) {
url.append(createURL(index));
// Append path
if (urlSegment.pathname) {
url.pathname =
withTrailingSlash(url.pathname) +
withoutLeadingSlash(urlSegment.pathname);
}

// Override hash
if (urlSegment.hash && urlSegment.hash !== "#") {
url.hash = urlSegment.hash;
}

// Append search
if (urlSegment.search && urlSegment.search !== "?") {
if (url.search && url.search !== "?") {
const queryString = stringifyQuery({
...parseQuery(url.search),
...parseQuery(urlSegment.search),
});
url.search = queryString.length > 0 ? "?" + queryString : "";
} else {
url.search = urlSegment.search;
}
}
}

return url.toString();
return stringifyParsedURL(url);
}

export function isSamePath(p1: string, p2: string) {
Expand Down
12 changes: 4 additions & 8 deletions test/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { resolveURL } from "../src";

describe("resolveURL", () => {
const tests = [
test.each([
{ input: [], out: "" },
{ input: ["/"], out: "/" },
{ input: ["/a"], out: "/a" },
Expand All @@ -12,13 +12,9 @@ describe("resolveURL", () => {
{ input: ["/a?foo=bar#123", "b/", "c/"], out: "/a/b/c/?foo=bar#123" },
{ input: ["http://foo.com", "a"], out: "http://foo.com/a" },
{ input: ["a?x=1", "b?y=2&y=3&z=4"], out: "a/b?x=1&y=2&y=3&z=4" },
];

for (const t of tests) {
test(t.input.toString(), () => {
expect(resolveURL(...t.input)).toBe(t.out);
});
}
])("$input -> $out", (t) => {
expect(resolveURL(...t.input)).toBe(t.out);
});

test("invalid URL (null)", () => {
// eslint-disable-next-line unicorn/no-null
Expand Down

0 comments on commit 3b66d62

Please sign in to comment.