48 lines
1.7 KiB
TypeScript
48 lines
1.7 KiB
TypeScript
import type { AuthResponse } from '$lib/types.js';
|
|
import { authStore } from '$lib/stores/auth.store.svelte.js';
|
|
|
|
const BASE = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
|
|
|
|
/**
|
|
* fetch() wrapper that automatically attaches the JWT Bearer token.
|
|
* Use this for all API calls that require authentication.
|
|
*/
|
|
export function authFetch(url: string, init: RequestInit = {}): Promise<Response> {
|
|
const token = authStore.token;
|
|
const headers = new Headers(init.headers);
|
|
if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
|
if (token) headers.set('Authorization', `Bearer ${token}`);
|
|
return fetch(url, { ...init, headers });
|
|
}
|
|
|
|
export async function login(email: string, password: string): Promise<AuthResponse> {
|
|
const res = await fetch(`${BASE}/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
if (!res.ok) {
|
|
const { error } = await res.json().catch(() => ({ error: 'Login failed' }));
|
|
throw new Error(error ?? 'Login failed');
|
|
}
|
|
return res.json() as Promise<AuthResponse>;
|
|
}
|
|
|
|
export async function register(
|
|
email: string,
|
|
password: string,
|
|
role: 'trader' | 'viewer' = 'viewer',
|
|
inviteCode = '',
|
|
): Promise<AuthResponse> {
|
|
const res = await fetch(`${BASE}/auth/register`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ email, password, role, inviteCode }),
|
|
});
|
|
if (!res.ok) {
|
|
const { error } = await res.json().catch(() => ({ error: 'Registration failed' }));
|
|
throw new Error(error ?? 'Registration failed');
|
|
}
|
|
return res.json() as Promise<AuthResponse>;
|
|
}
|