All files / src/api testConnection.ts

100% Statements 49/49
100% Branches 6/6
100% Functions 2/2
100% Lines 49/49

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 521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 3x 2x 2x 3x 1x 1x 1x 1x 1x 3x 3x 3x 1x 3x 2x 2x 3x      
/**
 * @file testConnection.ts
 * @description
 * Health checks for connectivity and session validity.
 * - `testConnection()` -> hits a cheap health endpoint; returns boolean.
 * - `checkSession()` -> fetches `/api/me`; returns user profile or null on 401.
 *
 * @remarks
 * - Keeps API calls separate from React components and hooks.
 * - Centralizes error handling for connectivity/session checks.
 */
import httpClient from './httpClient';
 
export type AppUserProfile = {
  id: string;
  fullName: string;
  email: string;
  role: string;
};
 
/**
 * Calls a cheap health endpoint to confirm **backend + DB** connectivity.
 * Returns true on HTTP 200; otherwise false.
 *
 * @remarks
 * - Uses your existing `/health/db` path.
 * - If you later expose `/actuator/health` you can add a fallback branch.
 */
export async function testConnection(): Promise<boolean> {
  try {
    const res = await httpClient.get('/api/health/db');
    return res.status === 200;
  } catch {
    return false;
  }
}
 
/**
 * Checks if a session is currently valid by fetching `/api/me`.
 * Returns the user profile on success, or `null` when not authenticated.
 */
export async function checkSession(): Promise<AppUserProfile | null> {
  try {
    const res = await httpClient.get<AppUserProfile>('/api/me');
    return res.data;
  } catch {
    return null;
  }
}