Skip to content

Commit

Permalink
fix: resolve relative paths when creating URLs (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeldwan authored and mrkurt committed Dec 20, 2018
1 parent 692a1b8 commit 931d948
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/v8env/src/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class URL {
password: baseParts.password,
hostname: baseParts.hostname,
port: baseParts.port,
path: urlParts.path || baseParts.path,
path: resolvePathFromBase(urlParts.path, baseParts.path),
query: urlParts.query || baseParts.query,
hash: urlParts.hash
}
Expand Down Expand Up @@ -280,4 +280,14 @@ export class URL {
}
}

function resolvePathFromBase(path: string, basePath: string) {
if (path.startsWith("/")) {
return path
}
if (basePath.endsWith("/")) {
return basePath + path
}
return basePath + "/" + path
}

URL.init()
24 changes: 24 additions & 0 deletions tests/v8env/tests/url.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { expect } from "chai"

describe("URL", () => {
it("ensures pathname begins with a slash", () => {
const url = new URL("https://fly.io/about")
url.pathname = "team"
expect(url.pathname).to.equal("/team")
})

it("resolves a relative path from a base", () => {
const url = new URL("fly", new URL("https://github.com/superfly/"))
expect(url.pathname).to.equal("/superfly/fly")
})

it("resolves an absolte path from a base", () => {
const url = new URL("/about", new URL("https://fly.io/path/"))
expect(url.pathname).to.equal("/about")
})

it("inserts trailing slash if needed", () => {
const url = new URL("fly", new URL("https://github.com/superfly"))
expect(url.pathname).to.equal("/superfly/fly")
})
})

0 comments on commit 931d948

Please sign in to comment.