All files / src/services api.ts

89.13% Statements 41/46
92.3% Branches 12/13
70% Functions 7/10
89.13% Lines 41/46

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 16572x   72x       72x 72x         72x   72x             42x 42x 42x 42x 42x 42x         5x 5x                                 27x       27x           27x 20x 20x     27x 24x     27x         27x           3x 2x             24x 5x 5x     19x       19x     72x             72x 3x         72x 15x                 72x 6x                   72x                   72x 1x                   72x                    
import { API_BASE_URL } from '@/config/apiBaseUrl';
import { ErrorResponse } from '@/models/auth';
import {
  getCurrentSession,
  refreshSession,
} from '@/services/sessionManager';
import { getCurrentLocale } from '@/contexts/LocaleContext';
import {
  localizeApiErrorDetails,
  localizeApiErrorMessage,
} from '@/utils/apiErrorLocalization';
 
export const BASE_URL = API_BASE_URL;
 
export class ApiError extends Error {
  code: string;
  status: number;
  details?: Record<string, string>;
  originalMessage: string;
 
  constructor(status: number, body: ErrorResponse) {
    super(localizeApiErrorMessage(body.error.message));
    this.name = 'ApiError';
    this.code = body.error.code;
    this.status = status;
    this.details = localizeApiErrorDetails(body.error.details);
    this.originalMessage = body.error.message;
  }
}
 
async function parseErrorResponse(response: Response): Promise<ErrorResponse> {
  try {
    return await response.json();
  } catch {
    return {
      error: {
        code: 'unknown_error',
        message: 'An unexpected error occurred.',
      },
    };
  }
}
 
async function requestJson<T>(
  endpoint: string,
  init: RequestInit,
  options?: { token?: string; requiresAuth?: boolean; hasRetried?: boolean },
): Promise<T> {
  const activeToken =
    options?.requiresAuth
      ? getCurrentSession()?.access_token ?? options?.token
      : undefined;
 
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept-Language': getCurrentLocale(),
    ...(init.headers as Record<string, string> | undefined),
  };
 
  if (init.method === 'GET') {
    headers['Cache-Control'] = 'no-store';
    headers.Pragma = 'no-cache';
  }
 
  if (activeToken) {
    headers.Authorization = `Bearer ${activeToken}`;
  }
 
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...init,
    headers,
  });
 
  if (
    options?.requiresAuth &&
    response.status === 401 &&
    !options?.hasRetried &&
    getCurrentSession()?.refresh_token
  ) {
    const refreshedSession = await refreshSession();
    return requestJson<T>(endpoint, init, {
      ...options,
      token: refreshedSession.access_token,
      hasRetried: true,
    });
  }
 
  if (!response.ok) {
    const errorBody = await parseErrorResponse(response);
    throw new ApiError(response.status, errorBody);
  }
 
  Iif (response.status === 204) {
    return undefined as T;
  }
 
  return response.json();
}
 
export async function apiPost<T>(endpoint: string, body: unknown): Promise<T> {
  return requestJson<T>(endpoint, {
    method: 'POST',
    body: JSON.stringify(body),
  });
}
 
export async function apiGet<T>(endpoint: string): Promise<T> {
  return requestJson<T>(endpoint, {
    method: 'GET',
  });
}
 
export async function apiGetAuth<T>(endpoint: string, token: string): Promise<T> {
  return requestJson<T>(
    endpoint,
    {
      method: 'GET',
    },
    { token, requiresAuth: true },
  );
}
 
export async function apiPostAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return requestJson<T>(
    endpoint,
    {
      method: 'POST',
      body: JSON.stringify(body),
    },
    { token, requiresAuth: true },
  );
}
 
export async function apiDeleteAuth<T>(endpoint: string, token: string): Promise<T> {
  return requestJson<T>(
    endpoint,
    {
      method: 'DELETE',
    },
    { token, requiresAuth: true },
  );
}
 
export async function apiPatchAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return requestJson<T>(
    endpoint,
    {
      method: 'PATCH',
      body: JSON.stringify(body),
    },
    { token, requiresAuth: true },
  );
}
 
export async function apiPutAuth<T>(endpoint: string, body: unknown, token: string): Promise<T> {
  return requestJson<T>(
    endpoint,
    {
      method: 'PUT',
      body: JSON.stringify(body),
    },
    { token, requiresAuth: true },
  );
}