# All files / src/services api.ts

62.74% Statements 32/51
50% Branches 3/6
100% Functions 3/3
62.74% Lines 32/51

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
    701x

    1x
    1x

    3x
    3x
    3x

    3x
    3x
    3x
    3x

    3x
    3x

    3x
    3x
    3x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    1x

    1x
    1x
    1x

    1x

    1x
     import axios from 'axios';

    const LOCAL_API_BASE_URL = 'http://localhost:3001/api';
    const LEGACY_API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

    function stripTrailingSlash(value: string): string {
      return value.replace(/\/+$/, '');
    }

    function ensureApiPath(value: string): string {
      const normalizedValue = stripTrailingSlash(value);
      return normalizedValue.endsWith('/api') ? normalizedValue : `${normalizedValue}/api`;
    }

    function resolveApiBaseUrl(): string {
      const configuredApiUrl = import.meta.env.VITE_API_URL || LEGACY_API_BASE_URL;

      if (configuredApiUrl) {
        return ensureApiPath(configuredApiUrl);
      }

      if (typeof window !== 'undefined') {
        const { protocol, hostname } = window.location;
        const isLocalDevelopmentHost = ['localhost', '127.0.0.1', '0.0.0.0'].includes(hostname);

        if (isLocalDevelopmentHost) {
          return LOCAL_API_BASE_URL;
        }

        if (hostname.startsWith('api.')) {
          return `${protocol}//${hostname}/api`;
        }

        return `${protocol}//api.${hostname}/api`;
      }

      return LOCAL_API_BASE_URL;
    }

    export const API_BASE_URL = resolveApiBaseUrl();

    export const apiClient = axios.create({
      baseURL: API_BASE_URL,
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // Request interceptor
    apiClient.interceptors.request.use(
      (config) => {
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // Response interceptor
    apiClient.interceptors.response.use(
      (response) => response,
      (error) => {
        return Promise.reject(error);
      }
    );

    // Default export for convenience
    export default apiClient;