2022-09-04 02:42:03 +00:00
|
|
|
const parts = {
|
2022-09-09 22:46:53 +00:00
|
|
|
host: "http://localhost.com",
|
|
|
|
prefix: "/api/v1",
|
2022-09-04 02:42:03 +00:00
|
|
|
};
|
2022-08-31 00:06:57 +00:00
|
|
|
|
2022-09-05 00:55:52 +00:00
|
|
|
export function overrideParts(host: string, prefix: string) {
|
2022-09-04 02:42:03 +00:00
|
|
|
parts.host = host;
|
|
|
|
parts.prefix = prefix;
|
|
|
|
}
|
|
|
|
|
|
|
|
export type QueryValue = string | string[] | number | number[] | boolean | null | undefined;
|
2022-08-31 00:06:57 +00:00
|
|
|
|
2022-09-05 00:55:52 +00:00
|
|
|
/**
|
2023-07-23 04:11:29 +00:00
|
|
|
* route is the main URL builder for the API. It will use a predefined host and prefix (global)
|
|
|
|
* in the urls.ts file and then append the passed-in path parameter using the `URL` class from the
|
2022-09-05 00:55:52 +00:00
|
|
|
* browser. It will also append any query parameters passed in as the second parameter.
|
|
|
|
*
|
|
|
|
* The default host `http://localhost.com` is removed from the path if it is present. This allows us
|
|
|
|
* to bootstrap the API with different hosts as needed (like for testing) but still allows us to use
|
2023-07-23 04:11:29 +00:00
|
|
|
* relative URLs in production because the API and client bundle are served from the same server/host.
|
2022-09-05 00:55:52 +00:00
|
|
|
*/
|
|
|
|
export function route(rest: string, params: Record<string, QueryValue> = {}): string {
|
2022-09-04 02:42:03 +00:00
|
|
|
const url = new URL(parts.prefix + rest, parts.host);
|
2022-08-31 00:06:57 +00:00
|
|
|
|
2022-09-04 02:42:03 +00:00
|
|
|
for (const [key, value] of Object.entries(params)) {
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
for (const item of value) {
|
|
|
|
url.searchParams.append(key, String(item));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
url.searchParams.append(key, String(value));
|
|
|
|
}
|
|
|
|
}
|
2022-08-31 00:06:57 +00:00
|
|
|
|
2022-09-09 22:46:53 +00:00
|
|
|
return url.toString().replace("http://localhost.com", "");
|
2022-08-31 00:06:57 +00:00
|
|
|
}
|