All files / src/core/services/http http.service.tsx

59.01% Statements 72/122
62.5% Branches 10/16
66.66% Functions 8/12
59.01% Lines 72/122

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 1411x 1x 1x 1x   1x   10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 2x 2x 2x     2x   10x 2x 2x 2x 2x 2x           2x   10x 12x 12x 12x 12x 12x 12x 12x 12x 12x   10x 10x 2x 2x 2x 2x 10x   10x 10x             10x                           10x 10x   10x 2x 2x 2x 2x 2x 2x         2x   10x 2x 2x 2x 2x 2x   10x               10x               10x               10x           10x   1x  
import { environment as env } from '@/environments/environment';
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
import { EHttpMethod } from './http.enum';
import { toHttpParams } from './http.utils';
import { IParams } from './http.models';
import { useGlobalStore } from '@/store/useGlobalStore';
 
class HttpService {
  private http: AxiosInstance;
  private baseURL = env.SERVER_API_URL;
  private pendingRequests = 0;
 
  constructor(baseURL?: string) {
    this.baseURL = baseURL || env.SERVER_API_URL;
    this.http = axios.create({
      baseURL: this.baseURL,
      withCredentials: false,
      headers: this.setupHeaders(),
    });
    this.injectInterceptors();
  }
 
  shouldIgnoreLoader = (config: AxiosRequestConfig): boolean => {
    try {
      return config.headers?.['ignoreLoader']?.toString() === 'true';
    } catch {
      return false;
    }
  };
 
  private changeLoadingState(start: boolean) {
    const { setIsLoading } = useGlobalStore.getState();
    if (start) {
      this.pendingRequests++;
      setIsLoading(true);
    } else {
      this.pendingRequests = Math.max(0, this.pendingRequests - 1);
      if (this.pendingRequests === 0) {
        setIsLoading(false);
      }
    }
  }
 
  private setupHeaders(extraHeaders?: Record<string, any>): Record<string, string> {
    const { hasAttachment, ...rest } = extraHeaders || {};
    return {
      'Content-Type': hasAttachment ? 'multipart/form-data' : 'application/json',
      'x-client-version': import.meta.env.VITE_APP_VERSION ?? 'dev',
      'x-trace-id': crypto.randomUUID?.() ?? Date.now().toString(),
      'x-locale': localStorage.getItem('lang') ?? 'en',
      ...rest,
    };
  }
 
  private injectInterceptors(): void {
    this.http.interceptors.request.use((config) => {
      if (!this.shouldIgnoreLoader(config)) {
        this.changeLoadingState(true);
      }
      return config;
    });
 
    this.http.interceptors.response.use(
      (response) => {
        if (!this.shouldIgnoreLoader(response.config)) {
          this.changeLoadingState(false);
        }
        delete response.config.headers?.ignoreLoader;
        return response;
      },
      async (error) => {
        if (!this.shouldIgnoreLoader(error.config)) {
          this.changeLoadingState(false);
        }
 
        const status = error.response?.status;
        const message = error.response?.data?.error || error.message;
 
        if (status === 404) {
          return Promise.reject(new Error(`Not found: ${message}`));
        }
 
        return Promise.reject(error);
      }
    );
  }
 
  private async request<T>(method: EHttpMethod, url: string, options: AxiosRequestConfig): Promise<T> {
    try {
      const response: AxiosResponse<T> = await this.http.request<T>({
        method,
        url,
        ...options,
      });
      return response.data;
    } catch (error) {
      return Promise.reject(error);
    }
  }
 
  public async get<T>(url: string, params?: any, extraHeaders: Record<string, any> = {}): Promise<T> {
    return this.request<T>(EHttpMethod.GET, url, {
      params: toHttpParams(params),
      headers: this.setupHeaders(extraHeaders),
    });
  }
 
  public async post<T, P>(url: string, payload: P, params?: IParams, extraHeaders: Record<string, any> = {}): Promise<T> {
    return this.request<T>(EHttpMethod.POST, url, {
      params: toHttpParams(params),
      data: payload,
      headers: this.setupHeaders(extraHeaders),
    });
  }
 
  public async put<T, P>(url: string, payload: P, params?: IParams, extraHeaders: Record<string, any> = {}): Promise<T> {
    return this.request<T>(EHttpMethod.PUT, url, {
      params: toHttpParams(params),
      data: payload,
      headers: this.setupHeaders(extraHeaders),
    });
  }
 
  public async patch<T, P>(url: string, payload: P, params?: IParams, extraHeaders: Record<string, any> = {}): Promise<T> {
    return this.request<T>(EHttpMethod.PATCH, url, {
      params: toHttpParams(params),
      data: payload,
      headers: this.setupHeaders(extraHeaders),
    });
  }
 
  public async delete<T>(url: string, params?: IParams, extraHeaders: Record<string, any> = {}): Promise<T> {
    return this.request<T>(EHttpMethod.DELETE, url, {
      params: toHttpParams(params),
      headers: this.setupHeaders(extraHeaders),
    });
  }
}
 
export default HttpService;