S SmartDocs
Chuỗi bài: Ricky typescript 40 dòng · Cập nhật 2026-04-14

publicUrl.ts

Ricky/Cat Project Final/fp_fixed /src/lib/publicUrl.ts

/**
 * Base URL for API and uploaded assets.
 * Set NEXT_PUBLIC_API_BASE to "" (empty) to use same-origin URLs (/api/..., /uploads/...).
 * Omit or leave unset for local dev default http://localhost:5050.
 */
export function getPublicApiBase(): string {
  const raw = process.env.NEXT_PUBLIC_API_BASE;
  if (raw === "") return "";
  if (raw == null || raw === undefined) return "http://localhost:5050";
  return String(raw).replace(/\/$/, "");
}

/**
 * Map legacy /uploads/... paths to /api/uploads/... so images load when nginx only proxies /api/ to Flask.
 */
export function mapLegacyUploadPath(path: string): string {
  if (path === "/uploads" || path.startsWith("/uploads/")) {
    return `/api/uploads${path.slice("/uploads".length)}`;
  }
  return path;
}

/** Absolute or same-origin URL for paths returned by the API (e.g. /uploads/..., /api/uploads/...). */
export function publicAssetUrl(path: string | undefined | null): string {
  if (path == null) return "";
  const p = String(path).trim();
  if (!p) return "";
  if (/^https?:\/\//i.test(p)) return p;
  let normalized = p.startsWith("/") ? p : `/${p}`;
  normalized = mapLegacyUploadPath(normalized);
  const base = getPublicApiBase();
  return base ? `${base}${normalized}` : normalized;
}

/** Build /api/... URL for fetch(). */
export function apiUrl(apiPath: string): string {
  const path = apiPath.startsWith("/") ? apiPath : `/${apiPath}`;
  const base = getPublicApiBase();
  return base ? `${base}${path}` : path;
}

Bài viết liên quan