🚿 Adds api function to ensure a host
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
import { user } from '$lib/stores/user';
|
import { user } from '$lib/stores/user';
|
||||||
import { get } from 'svelte/store';
|
import { get } from 'svelte/store';
|
||||||
import { Err, Ok, type Result } from './utilities';
|
import { Err, Ok, type Result } from './utilities';
|
||||||
|
import { location } from './stores';
|
||||||
|
|
||||||
export namespace api {
|
export namespace api {
|
||||||
export function get<TResponse>(endpoint: string, params?: RequestInit) {
|
export function get<TResponse>(endpoint: string, params?: RequestInit) {
|
||||||
@@ -26,6 +27,7 @@ async function sendRequest<TResponse>(
|
|||||||
data?: unknown,
|
data?: unknown,
|
||||||
params?: RequestInit
|
params?: RequestInit
|
||||||
): Promise<Result<TResponse, Error>> {
|
): Promise<Result<TResponse, Error>> {
|
||||||
|
endpoint = resolveUrl(endpoint);
|
||||||
const user_token = get(user).bearer_token;
|
const user_token = get(user).bearer_token;
|
||||||
const body = data !== null && typeof data !== 'undefined' ? JSON.stringify(data) : undefined;
|
const body = data !== null && typeof data !== 'undefined' ? JSON.stringify(data) : undefined;
|
||||||
|
|
||||||
@@ -66,6 +68,12 @@ async function sendRequest<TResponse>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveUrl(url: string): string {
|
||||||
|
if (url.startsWith('http') || !get(location)) return url;
|
||||||
|
const protocol = window.location.protocol;
|
||||||
|
return `${protocol}//${get(location)}${url.startsWith('/') ? '' : '/'}${url}`;
|
||||||
|
}
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
constructor(public readonly response: Response) {
|
constructor(public readonly response: Response) {
|
||||||
super(`${response.status}`);
|
super(`${response.status}`);
|
||||||
|
|||||||
Reference in New Issue
Block a user