File size: 1,079 Bytes
6b45861 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import { get } from 'svelte/store';
import { authStore } from '$lib/stores/auth';
/**
* Make an authenticated fetch request with Bearer token
* Automatically adds Authorization header if user is logged in
*/
export async function authenticatedFetch(url: string, options: RequestInit = {}): Promise<Response> {
const auth = get(authStore);
const headers = new Headers(options.headers);
// Add auth token if available
if (auth.session?.accessToken) {
headers.set('Authorization', `Bearer ${auth.session.accessToken}`);
}
// Ensure JSON content type
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
return fetch(url, {
...options,
headers
});
}
/**
* Make an authenticated JSON request and parse response
*/
export async function authenticatedJson<T = any>(url: string, options: RequestInit = {}): Promise<T> {
const response = await authenticatedFetch(url, options);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
|