feat(frontend): add apiFetch wrapper for automatic auth token injection
Centralizes auth token management into a reusable apiFetch() helper and getAuthHeaders() utility, eliminating inline Bearer token logic across all frontend files. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { resolve } from '$app/paths';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch, getAuthHeaders } from '$lib/utils/api';
|
||||
import { ensureBusinessInfo, getBusinessInfo } from '$lib/stores/businessInfo.svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { onDestroy } from 'svelte';
|
||||
@@ -207,9 +208,7 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
headers: authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {}
|
||||
});
|
||||
const response = await apiFetch('/api/user/profile');
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
userDepositsRequired = user.deposits_required ?? 0;
|
||||
@@ -229,9 +228,7 @@
|
||||
_activeBookingCheckDone = false;
|
||||
try {
|
||||
// Check for pending bookings
|
||||
const pendingResp = await fetch('/api/bookings?status=pending&perPage=1', {
|
||||
headers: authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {}
|
||||
});
|
||||
const pendingResp = await apiFetch('/api/bookings?status=pending&perPage=1');
|
||||
if (pendingResp.ok) {
|
||||
const data = await pendingResp.json();
|
||||
if (data.bookings && data.bookings.length > 0) {
|
||||
@@ -242,9 +239,7 @@
|
||||
}
|
||||
|
||||
// Check for confirmed bookings
|
||||
const confirmedResp = await fetch('/api/bookings?status=confirmed&perPage=1', {
|
||||
headers: authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {}
|
||||
});
|
||||
const confirmedResp = await apiFetch('/api/bookings?status=confirmed&perPage=1');
|
||||
if (confirmedResp.ok) {
|
||||
const data = await confirmedResp.json();
|
||||
hasActiveBooking = data.bookings && data.bookings.length > 0;
|
||||
@@ -270,11 +265,7 @@
|
||||
async function fetchDiscountPreview() {
|
||||
if (!confirmedBooking?.id) return;
|
||||
try {
|
||||
const resp = await fetch(`/api/bookings/${confirmedBooking.id}/discount-preview`, {
|
||||
headers: authStore.currentToken
|
||||
? { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
: undefined
|
||||
});
|
||||
const resp = await apiFetch(`/api/bookings/${confirmedBooking.id}/discount-preview`);
|
||||
if (resp.ok) {
|
||||
const data = await resp.json();
|
||||
// Only show time-based (auto-apply) discounts on the confirmation screen
|
||||
@@ -321,11 +312,11 @@
|
||||
|
||||
paymentAttempted = true;
|
||||
|
||||
const response = await fetch(`/api/bookings/${bookingId}/payment`, {
|
||||
const response = await apiFetch(`/api/bookings/${bookingId}/payment`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {})
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
@@ -397,11 +388,11 @@
|
||||
const startTimeISO = formatLocalDateTime(bookingDate);
|
||||
const serviceIds = selectedServices.map((s) => s.id);
|
||||
|
||||
const response = await fetch('/api/bookings/reserve', {
|
||||
const response = await apiFetch('/api/bookings/reserve', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {})
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({ start_time: startTimeISO, service_ids: serviceIds })
|
||||
});
|
||||
@@ -453,10 +444,7 @@
|
||||
window.__bookingFlowCountdownInterval = null;
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/bookings/reserve', {
|
||||
method: 'DELETE',
|
||||
headers: authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {}
|
||||
});
|
||||
const res = await apiFetch('/api/bookings/reserve', { method: 'DELETE' });
|
||||
if (!res.ok) console.warn('Failed to release reservation', idToRelease, res.status);
|
||||
} catch (e) {
|
||||
console.warn('Error releasing reservation', idToRelease, e);
|
||||
@@ -529,13 +517,7 @@
|
||||
async function fetchServices() {
|
||||
servicesLoading = true;
|
||||
try {
|
||||
const response = await fetch('/api/services', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(authStore.currentToken ? { Authorization: `Bearer ${authStore.currentToken}` } : {})
|
||||
}
|
||||
});
|
||||
const response = await apiFetch('/api/services');
|
||||
|
||||
if (response.ok) {
|
||||
const data: Service[] = await response.json();
|
||||
@@ -729,16 +711,9 @@
|
||||
loadingAvailableHours = true;
|
||||
|
||||
try {
|
||||
const authHeaders: RequestInit['headers'] = authStore.currentToken
|
||||
? { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
: undefined;
|
||||
const [whRes, ahRes] = await Promise.all([
|
||||
fetch(`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`, {
|
||||
headers: authHeaders
|
||||
}),
|
||||
fetch(`/api/scheduling/available-hours?start=${startStr}&end=${endStr}`, {
|
||||
headers: authHeaders
|
||||
})
|
||||
apiFetch(`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`),
|
||||
apiFetch(`/api/scheduling/available-hours?start=${startStr}&end=${endStr}`)
|
||||
]);
|
||||
if (!whRes.ok || !ahRes.ok) {
|
||||
throw new Error(`HTTP error! wh: ${whRes.status}, ah: ${ahRes.status}`);
|
||||
@@ -829,14 +804,9 @@
|
||||
const startStr = startOfMonth.toString();
|
||||
const endStr = endOfMonth.toString();
|
||||
|
||||
const authHeaders: RequestInit['headers'] = authStore.currentToken
|
||||
? { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
: undefined;
|
||||
|
||||
// Fetch working hours
|
||||
const workingHoursResponse = await fetch(
|
||||
`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`,
|
||||
{ headers: authHeaders }
|
||||
const workingHoursResponse = await apiFetch(
|
||||
`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`
|
||||
);
|
||||
if (!workingHoursResponse.ok) {
|
||||
throw new Error(`HTTP error! status: ${workingHoursResponse.status}`);
|
||||
@@ -860,9 +830,8 @@
|
||||
workingHours = { ...workingHours, ...workingHoursMap };
|
||||
|
||||
// Fetch available hours
|
||||
const availableHoursResponse = await fetch(
|
||||
`/api/scheduling/available-hours?start=${startStr}&end=${endStr}`,
|
||||
{ headers: authHeaders }
|
||||
const availableHoursResponse = await apiFetch(
|
||||
`/api/scheduling/available-hours?start=${startStr}&end=${endStr}`
|
||||
);
|
||||
if (!availableHoursResponse.ok) {
|
||||
throw new Error(`HTTP error! status: ${availableHoursResponse.status}`);
|
||||
@@ -1484,17 +1453,13 @@
|
||||
requestBody.user_id = guestUserId;
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': idempotencyKey
|
||||
};
|
||||
if (authStore.currentToken) {
|
||||
headers['Authorization'] = `Bearer ${authStore.currentToken}`;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/bookings', {
|
||||
const response = await apiFetch('/api/bookings', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': idempotencyKey,
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify(requestBody)
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user