Skip to content

Instantly share code, notes, and snippets.

@sheepla
Created March 24, 2024 03:38
Show Gist options
  • Save sheepla/d6d9265d6c1517c54b2c03b08db46509 to your computer and use it in GitHub Desktop.
Save sheepla/d6d9265d6c1517c54b2c03b08db46509 to your computer and use it in GitHub Desktop.
// 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