128 lines
4.3 KiB
TypeScript
128 lines
4.3 KiB
TypeScript
/**
|
|
* API Service Client with Token Interceptor, Tenant Context Header, and Error Boundaries.
|
|
*
|
|
* Fulfills FR-AUTH-001, FR-AUTH-002, FR-AUTH-003, and FR-TENANTMEMBERSHIPCONTEXT-002.
|
|
*/
|
|
import { authStore } from '../stores/authStore';
|
|
import { tenantStore } from '../stores/tenantStore';
|
|
|
|
const BASE_URL = (typeof process !== 'undefined' && process.env?.VITE_API_URL)
|
|
? process.env.VITE_API_URL
|
|
: (typeof window !== 'undefined' ? '' : 'http://localhost:8000');
|
|
|
|
export interface ApiResponse<T = any> {
|
|
data?: T;
|
|
error?: string;
|
|
status: number;
|
|
}
|
|
|
|
export interface ApiClientFn {
|
|
<T = any>(endpoint: string, options?: RequestInit): Promise<ApiResponse<T>>;
|
|
get<T = any>(endpoint: string, options?: RequestInit): Promise<T>;
|
|
post<T = any>(endpoint: string, body?: any, options?: RequestInit): Promise<T>;
|
|
patch<T = any>(endpoint: string, body?: any, options?: RequestInit): Promise<T>;
|
|
delete<T = any>(endpoint: string, options?: RequestInit): Promise<T>;
|
|
}
|
|
|
|
const baseApiClient = async function<T = any>(
|
|
endpoint: string,
|
|
options: RequestInit = {}
|
|
): Promise<ApiResponse<T>> {
|
|
const token = authStore.getState().accessToken;
|
|
const activeTenantId = tenantStore.getState().activeTenantId;
|
|
const headers = new Headers(options.headers || {});
|
|
|
|
headers.set('Accept', 'application/json');
|
|
if (token) {
|
|
headers.set('Authorization', `Bearer ${token}`);
|
|
}
|
|
if (activeTenantId && !headers.has('X-Tenant-ID')) {
|
|
headers.set('X-Tenant-ID', activeTenantId);
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${BASE_URL}${endpoint}`, {
|
|
...options,
|
|
headers,
|
|
});
|
|
|
|
// Catch 401 Unauthorized -> trigger client logout
|
|
if (response.status === 401) {
|
|
authStore.logout();
|
|
tenantStore.clearTenant();
|
|
if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
|
|
window.location.href = '/login?error=SESSION_EXPIRED';
|
|
}
|
|
return { status: 401, error: 'SESSION_EXPIRED' };
|
|
}
|
|
|
|
// Catch 403 Forbidden -> redirect or flag access denied
|
|
if (response.status === 403) {
|
|
const errBody = await response.json().catch(() => null);
|
|
if (errBody?.code === 'TENANT_NOT_ACTIVE') {
|
|
if (typeof window !== 'undefined') {
|
|
window.location.href = '/access-denied?reason=TENANT_SUSPENDED';
|
|
}
|
|
}
|
|
return { status: 403, error: errBody?.error || 'ACCESS_DENIED', data: errBody };
|
|
}
|
|
|
|
const data = await response.json().catch(() => null);
|
|
return { data, status: response.status };
|
|
} catch (err: any) {
|
|
return { status: 500, error: err.message || 'NETWORK_ERROR' };
|
|
}
|
|
};
|
|
|
|
export const apiClient = baseApiClient as ApiClientFn;
|
|
|
|
apiClient.get = async function<T = any>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
const res = await baseApiClient<T>(endpoint, { ...options, method: 'GET' });
|
|
if (res.status >= 400) {
|
|
const error: any = new Error(res.error || `HTTP ${res.status}`);
|
|
error.response = res;
|
|
throw error;
|
|
}
|
|
return res.data as T;
|
|
};
|
|
|
|
apiClient.post = async function<T = any>(endpoint: string, body?: any, options: RequestInit = {}): Promise<T> {
|
|
const res = await baseApiClient<T>(endpoint, {
|
|
...options,
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
if (res.status >= 400) {
|
|
const error: any = new Error(res.error || `HTTP ${res.status}`);
|
|
error.response = res;
|
|
throw error;
|
|
}
|
|
return res.data as T;
|
|
};
|
|
|
|
apiClient.patch = async function<T = any>(endpoint: string, body?: any, options: RequestInit = {}): Promise<T> {
|
|
const res = await baseApiClient<T>(endpoint, {
|
|
...options,
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
if (res.status >= 400) {
|
|
const error: any = new Error(res.error || `HTTP ${res.status}`);
|
|
error.response = res;
|
|
throw error;
|
|
}
|
|
return res.data as T;
|
|
};
|
|
|
|
apiClient.delete = async function<T = any>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
const res = await baseApiClient<T>(endpoint, { ...options, method: 'DELETE' });
|
|
if (res.status >= 400) {
|
|
const error: any = new Error(res.error || `HTTP ${res.status}`);
|
|
error.response = res;
|
|
throw error;
|
|
}
|
|
return res.data as T;
|
|
};
|