forked from UKSOURCE/ipv6
58 lines
1.9 KiB
TypeScript
58 lines
1.9 KiB
TypeScript
/**
|
|
* Build a safe image URL for assets coming from the CMS.
|
|
*
|
|
* Rules:
|
|
* - If already a full URL (http/https) → return as is
|
|
* - If starts with `/uploads/` or `/img/` → prepend API URL (NEXT_PUBLIC_API_URL or default localhost)
|
|
* - If starts with `/` → use as-is (served by Next/public)
|
|
* - Otherwise → treat as relative path under `/`
|
|
*/
|
|
export function getCmsImageUrl(imagePath: string | undefined): string {
|
|
if (!imagePath) return "";
|
|
|
|
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
|
|
return imagePath;
|
|
}
|
|
|
|
// Hỗ trợ cả "/uploads/", "uploads/", "/img/", "img/"
|
|
if (
|
|
imagePath.startsWith("/uploads/") ||
|
|
imagePath.startsWith("uploads/") ||
|
|
imagePath.startsWith("/img/") ||
|
|
imagePath.startsWith("img/")
|
|
) {
|
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
|
// Nếu thiếu dấu "/" đầu, thêm vào cho đúng path
|
|
const fixedPath =
|
|
imagePath.startsWith("/") ? imagePath : `/${imagePath}`;
|
|
return `${apiUrl}${fixedPath}`;
|
|
}
|
|
|
|
if (imagePath.startsWith("/")) {
|
|
return imagePath;
|
|
}
|
|
|
|
return `/${imagePath}`;
|
|
}
|
|
|
|
/**
|
|
* Get blog image URL with priority:
|
|
* 1. /assets/img/blog/blog-details/[filename] (high quality)
|
|
* 2. /assets/img/blog/[filename] (fallback)
|
|
*/
|
|
export function getBlogImageUrl(imagePath: string | undefined): string {
|
|
if (!imagePath) return "";
|
|
|
|
// Extract filename from path (e.g., "/assets/img/blog/UniversityCampus.png" → "UniversityCampus.png")
|
|
const filename = imagePath.split("/").pop() || "";
|
|
|
|
// Check if high quality version exists in blog-details
|
|
const highQualityPath = `/assets/img/blog/blog-details/${filename}`;
|
|
|
|
// Return high quality path if it exists, otherwise return original path
|
|
// Note: This assumes the file exists. If not, the browser will show broken image.
|
|
// In production, you might want to check file existence on server or use a fallback.
|
|
return highQualityPath;
|
|
}
|
|
|