forked from UKSOURCE/cms.hailearning.edu.vn
80 lines
2.4 KiB
JavaScript
80 lines
2.4 KiB
JavaScript
/**
|
|
* Thêm BACKEND_URL vào đường dẫn hình ảnh
|
|
* @param {Object} data - Dữ liệu cần xử lý
|
|
* @returns {Object} - Dữ liệu đã được xử lý với đường dẫn hình ảnh đầy đủ
|
|
*/
|
|
function addBaseUrlToImages(data, baseUrl) {
|
|
// Use passed baseUrl, then env var, then default to localhost:3001
|
|
const BACKEND_URL = (baseUrl || process.env.BACKEND_URL || "http://localhost:3001").replace(/\/$/, "");
|
|
|
|
// Tạo bản sao sâu để tránh thay đổi dữ liệu gốc
|
|
const processedData = JSON.parse(JSON.stringify(data));
|
|
|
|
// Hàm đệ quy để xử lý tất cả các URL hình ảnh trong đối tượng
|
|
const processObject = (obj) => {
|
|
if (!obj || typeof obj !== "object") return;
|
|
|
|
if (Array.isArray(obj)) {
|
|
obj.forEach((item, index) => {
|
|
if (typeof item === "string" && (item.startsWith("/uploads/") || item.startsWith("/assets/img/"))) {
|
|
if (!item.startsWith("http")) {
|
|
obj[index] = `${BACKEND_URL}${item}`;
|
|
}
|
|
} else if (typeof item === "object") {
|
|
processObject(item);
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
Object.keys(obj).forEach((key) => {
|
|
const value = obj[key];
|
|
if (typeof value === "string" && (value.startsWith("/uploads/") || value.startsWith("/assets/img/"))) {
|
|
if (!value.startsWith("http")) {
|
|
obj[key] = `${BACKEND_URL}${value}`;
|
|
}
|
|
} else if (value && typeof value === "object") {
|
|
processObject(value);
|
|
}
|
|
});
|
|
};
|
|
|
|
processObject(processedData);
|
|
return processedData;
|
|
}
|
|
|
|
/**
|
|
* Tạo full URL cho ảnh từ đường dẫn tương đối - dùng cho EJS templates
|
|
* @param {string} imagePath - Đường dẫn ảnh
|
|
* @param {string} backendUrl - Backend URL (optional, sẽ lấy từ env nếu không có)
|
|
* @returns {string} - Full URL của ảnh
|
|
*/
|
|
function getFullImageUrl(imagePath, backendUrl = null) {
|
|
if (!imagePath) return "";
|
|
|
|
// Nếu đã là full URL thì return luôn
|
|
if (imagePath.startsWith("http")) {
|
|
return imagePath;
|
|
}
|
|
|
|
// Lấy backend URL
|
|
const baseUrl = (
|
|
backendUrl ||
|
|
process.env.BACKEND_URL ||
|
|
"http://localhost:3001"
|
|
).replace(/\/$/, "");
|
|
|
|
// Xử lý đường dẫn
|
|
let imgSrc = imagePath;
|
|
if (!imgSrc.startsWith("/")) {
|
|
imgSrc = "/" + imgSrc;
|
|
}
|
|
|
|
return baseUrl + imgSrc;
|
|
}
|
|
|
|
module.exports = {
|
|
addBaseUrlToImages,
|
|
getFullImageUrl,
|
|
};
|