All files / src/services api.ts

81.39% Statements 35/43
77.77% Branches 14/18
40% Functions 4/10
81.39% Lines 35/43

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 15738x   38x         38x   38x           26x 26x 26x 26x 26x         2x 2x                                 14x       14x         14x 14x 14x     14x 14x     14x         14x           3x 2x             11x 2x 2x     9x       9x     38x             38x           38x 12x                 38x                     38x                   38x                     38x                    
import { API_BASE_URL } from '@/config/apiBaseUrl';
import { ErrorResponse } from '@/models/auth';
import {
  getCurrentSession,
  refreshSession,
} from '@/services/sessionManager';
 
export const BASE_URL = API_BASE_URL;
 
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 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',
    ...(init.headers as Record<string, string> | undefined),
  };
 
  Eif (init.method === 'GET') {
    headers['Cache-Control'] = 'no-store';
    headers.Pragma = 'no-cache';
  }
 
  Eif (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 },
  );
}