All files / src/api apiBaseUrl.ts

64.28% Statements 9/14
61.53% Branches 8/13
100% Functions 0/0
64.28% Lines 9/14

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 6062x 62x     62x                 62x     62x           62x                       5723x                                 129611x     129611x          
const API_PREFIX = "/api/";
const FALLBACK_ORIGIN = "http://localhost";
 
function ensureTrailingSlash(url: string): string {
  return url.endsWith("/") ? url : `${url}/`;
}
 
export function resolveApiBaseUrl(
  configuredBaseUrl = import.meta.env.VITE_API_BASE_URL,
  currentOrigin = typeof window !== "undefined"
    ? window.location.origin
    : FALLBACK_ORIGIN,
): string {
  const trimmedBaseUrl = configuredBaseUrl?.trim();
 
  if (trimmedBaseUrl) {
    return ensureTrailingSlash(trimmedBaseUrl);
  }
 
  return new URL(API_PREFIX, currentOrigin).toString();
}
 
export const baseUrl = resolveApiBaseUrl();
 
export function resolveApiUrl(path: string, apiBaseUrl = baseUrl): string {
  // Leave fully-qualified URLs untouched so callers can still opt into an explicit host.
  // This matches standard schemes such as http:, https:, ws:, and wss:.
  if (/^[a-z][a-z\d+.-]*:/i.test(path)) {
    return path;
  }
 
  // Generated endpoints already include `/api/...`, so resolve them against the current
  // origin without appending a second `/api` segment when the default base also ends in `/api/`.
  if (path.startsWith("/api/")) {
    return new URL(path, apiBaseUrl).toString();
  }
 
  // Treat `/api` itself as the API root so callers can request the prefix directly.
  if (path === "/api" || path === "api") {
    return new URL("./", apiBaseUrl).toString();
  }
 
  return new URL(path, apiBaseUrl).toString();
}
 
export function resolveNotificationEndpointUrl(
  configuredUrl = import.meta.env.VITE_NOTIFICATION_ENDPOINT_URL,
  currentOrigin = typeof window !== "undefined"
    ? window.location.origin
    : FALLBACK_ORIGIN,
): string {
  const trimmedUrl = configuredUrl?.trim();
 
  if (trimmedUrl) {
    return trimmedUrl;
  }
 
  return new URL("/api/notifications/", currentOrigin).toString();
}