Created
March 24, 2024 03:38
-
-
Save sheepla/d6d9265d6c1517c54b2c03b08db46509 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Build URL safely in TypeScript (Deno) | |
// | |
// See: | |
// https://developer.mozilla.org/ja/docs/Web/API/URL | |
// https://developer.mozilla.org/ja/docs/Web/API/URLSearchParams | |
import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; | |
export function buildURL( | |
base: string, | |
path: string, | |
query: string | Iterable<string[]> | Record<string, string>, | |
): URL { | |
const url = new URL(base); | |
url.pathname = path; | |
const params = new URLSearchParams(query); | |
url.search = params.toString(); | |
return url; | |
} | |
[ | |
{ | |
// When query is string | |
want: "https://www.example.com/search?foo=foofoo&bar=barbar", | |
have: buildURL("https://www.example.com", "/search", "foo=foofoo&bar=barbar").href, | |
}, | |
{ | |
// When query is Iterable<string[]> | |
want: "https://www.example.com/search?foo=foofoo&bar=barbar", | |
have: buildURL("https://www.example.com", "/search", [ | |
["foo", "foofoo"], | |
["bar", "barbar"], | |
]).href, | |
}, | |
{ | |
// When query is Record<string,string> | |
want: "https://www.example.com/search?foo=foofoo&bar=barbar", | |
have: buildURL("https://www.example.com", "/search", { | |
foo: "foofoo", | |
bar: "barbar" | |
}).href, | |
}, | |
].map((testcase) => { | |
assertEquals(testcase.want, testcase.have) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment