All files / src/services api.ts

81.29% Statements 113/139
85.71% Branches 30/35
81.25% Functions 13/16
81.29% Lines 113/139

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 1861x 1x     1x 7x 7x 7x   7x 7x 7x 7x 7x 7x 7x 7x   3x 3x 3x 3x 3x 3x         3x                   1x 1x   79x 79x 79x 79x 79x 79x 79x   1x 27x 27x   8x 8x   7x 7x 7x   7x 7x 7x 7x 7x   7x 1x 1x     6x 6x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x   7x 7x                                           2x 2x 2x 2x 2x 2x   2x       2x 2x       70x 70x 70x 70x 70x 70x 70x 70x 70x 70x   70x 70x 70x   70x 70x   63x 63x 63x 63x 63x 63x 63x   63x 8x 7x 7x   31x 2x     31x 2x 2x   26x 26x   1x 47x 47x   1x 12x 12x   1x 4x 4x   1x       1x      
import { API_BASE_URL } from '@/config/api';
import { getCurrentLocale } from '@/i18n';
import { AuthSessionResponse, ErrorResponse } from '@/models/auth';
 
export class ApiError extends Error {
  code: string;
  status: number;
  details?: Record<string, string>;
 
  constructor(status: number, body: ErrorResponse) {
    super(body.error.message);
    this.name = 'ApiError';
    this.code = body.error.code;
    this.status = status;
    this.details = body.error.details;
  }
}
 
async function handleErrorResponse(response: Response): Promise<never> {
  try {
    const errorBody: ErrorResponse = await response.json();
    throw new ApiError(response.status, errorBody);
  } catch (err) {
    if (err instanceof ApiError) throw err;
    throw new ApiError(response.status, {
      error: { code: 'network_error', message: `Request failed (${response.status})` },
    });
  }
}
 
// --- Token refresh manager ---
 
interface TokenRefreshManager {
  getRefreshToken: () => string | null;
  onRefreshSuccess: (accessToken: string, refreshToken: string, username: string, role: AuthSessionResponse['user']['role']) => void;
  onRefreshFailure: () => void;
}
 
let tokenRefreshManager: TokenRefreshManager | null = null;
let pendingRefresh: Promise<string> | null = null;
 
function buildJsonHeaders(extraHeaders: Record<string, string> = {}): Record<string, string> {
  return {
    'Content-Type': 'application/json',
    'Accept-Language': getCurrentLocale(),
    ...extraHeaders,
  };
}
 
export function setTokenRefreshManager(manager: TokenRefreshManager | null): void {
  tokenRefreshManager = manager;
}
 
async function attemptTokenRefresh(): Promise<string> {
  if (pendingRefresh) return pendingRefresh;
 
  const doRefresh = async (): Promise<string> => {
    const refreshToken = tokenRefreshManager?.getRefreshToken();
    if (!refreshToken) throw new Error('No refresh token available');
 
    const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
      method: 'POST',
      headers: buildJsonHeaders(),
      body: JSON.stringify({ refresh_token: refreshToken }),
    });
 
    if (!response.ok) {
      tokenRefreshManager?.onRefreshFailure();
      await handleErrorResponse(response);
    }
 
    const session: AuthSessionResponse = await response.json();
    tokenRefreshManager?.onRefreshSuccess(
      session.access_token,
      session.refresh_token,
      session.user.username,
      session.user.role,
    );
    return session.access_token;
  };
 
  pendingRefresh = doRefresh().finally(() => {
    pendingRefresh = null;
  });
 
  return pendingRefresh;
}
 
// --- Public API helpers ---
 
export async function apiPost<T>(endpoint: string, body: unknown): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${endpoint}`, {
    method: 'POST',
    headers: buildJsonHeaders(),
    body: JSON.stringify(body),
  });
 
  if (!response.ok) {
    await handleErrorResponse(response);
  }
 
  if (response.status === 204) {
    return undefined as T;
  }
 
  return response.json();
}
 
export async function apiGet<T>(endpoint: string): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${endpoint}`, {
    method: 'GET',
    headers: buildJsonHeaders(),
    cache: 'no-store',
  });
 
  if (!response.ok) {
    await handleErrorResponse(response);
  }
 
  return response.json();
}
 
// --- Authenticated API helpers (with silent token refresh on 401) ---
 
async function fetchWithAuth(
  method: string,
  endpoint: string,
  token: string,
  body?: unknown,
): Promise<Response> {
  const headers: Record<string, string> = {
    ...buildJsonHeaders(),
    Authorization: `Bearer ${token}`,
  };
 
  const init: RequestInit = { method, headers };
  if (body !== undefined) init.body = JSON.stringify(body);
  if (method === 'GET') init.cache = 'no-store';
 
  return fetch(`${API_BASE_URL}${endpoint}`, init);
}
 
async function executeWithRefresh<T>(
  method: string,
  endpoint: string,
  token: string,
  body?: unknown,
): Promise<T> {
  let response = await fetchWithAuth(method, endpoint, token, body);
 
  if (response.status === 401 && tokenRefreshManager) {
    const newToken = await attemptTokenRefresh();
    response = await fetchWithAuth(method, endpoint, newToken, body);
  }
 
  if (!response.ok) {
    await handleErrorResponse(response);
  }
 
  if (response.status === 204) {
    return undefined as T;
  }
 
  return response.json();
}
 
export function apiGetAuth<T>(endpoint: string, token: string): Promise<T> {
  return executeWithRefresh<T>('GET', endpoint, token);
}
 
export function apiPostAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return executeWithRefresh<T>('POST', endpoint, token, body);
}
 
export function apiPatchAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return executeWithRefresh<T>('PATCH', endpoint, token, body);
}
 
export function apiPutAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return executeWithRefresh<T>('PUT', endpoint, token, body);
}
 
export function apiDeleteAuth<T>(endpoint: string, token: string): Promise<T> {
  return executeWithRefresh<T>('DELETE', endpoint, token);
}