URL
jstz
's implementation of the URL
API defines utilities for URL resolution and parsing according to the URL specification.
Quick Start
There are two ways to create a URL: either as an absolute URL or a relative URL.
let url: URL = new URL(`jstz://${my_function.address}/entrypoint`);
let url2: URL = new URL("../entrypoint_2", url.href);
Each jstz
smart function is assigned a unique address, akin to an IP address, starting with KT1
when the function is deployed.
To decode these addresses, jstz
employs its own URL scheme jstz://
.
An example URL for a jstz
smart function would therefore be jstz://KT19mYzcaYk55KttezwP4TbMrGCDpVuPW3Jw/
.
It's important to note that if the base URL or the resulting URL is not valid, the constructor will raise a TypeError
exception.
To check whether URLs can be parsed correctly, you can use the static method URL.canParse()
.
if (URL.canParse(relativePath, baseUrl)) {
let url = new URL(relativePath, baseUrl);
console.log(url.href);
} else {
// the URL cannot be parsed, take appropriate action.
console.error("Invalid URL");
}
You can also modify a URL by setting its properties.
let url = new URL("jstz://KT19mYzcaYk55KttezwP4TbMrGCDpVuPW3Jw/"); // not a valid address, we'll have to change it
url.hostname = Ledger.selfAddress;
url.pathname = "accounts";
url.hash = "#id";
console.log(url.href); // jstz://KT1../accounts#id
The URLSearchParams
API may be used to build and manipulate search parameters. To get the search parameters from the URL, you can make use of the .searchParams
instance property.
let url = new URL(`jstz://${address}/?first_name=Dave`);
switch (url.searchParams.get("first_name")) {
case "Jim":
url.searchParams.set("last_name", "Jones");
break;
case "Sarah":
url.searchParams.set("last_name", "Smith");
break;
case "Dave":
url.searchParams.set("last_name", "Davies");
break;
}
Constructor
new URL(url: string, base?: string): URL
Constructs a URL from a given URL string and an optional base URL.
If base
if present then url
will be interpreted as a relative URL.
If base
is not present then url
will be interpreted as an absolute URL.
Raises a TypeError
exception if the base URL or resulting URL aren't valid URLs.