forked from UKSOURCE/cms.hailearning.edu.vn
50 lines
1.6 KiB
JavaScript
50 lines
1.6 KiB
JavaScript
/**
|
|
* Prefix FRONTEND_URL to social share links stored as relative paths.
|
|
* - Deep-clones the input and only modifies values under `social.shareLinks` that
|
|
* are strings starting with '/'.
|
|
* - Leaves absolute URLs (http/https) unchanged.
|
|
* - Normalizes to avoid double slashes between FRONTEND_URL and the path.
|
|
*
|
|
* @param {Object} data - object that may contain `social.shareLinks` (e.g., blog object)
|
|
* @returns {Object} - deep-cloned object with prefixed share links
|
|
*/
|
|
function addFrontendUrlToShareLinks(data) {
|
|
const FRONTEND_URL = (process.env.FRONTEND_URL || '').replace(/\/$/, '');
|
|
|
|
if (!data || typeof data !== 'object') return data;
|
|
|
|
// Deep clone to avoid mutating original
|
|
const cloned = JSON.parse(JSON.stringify(data));
|
|
|
|
try {
|
|
if (cloned.social && typeof cloned.social === 'object') {
|
|
const share = cloned.social.shareLinks;
|
|
if (share && typeof share === 'object') {
|
|
Object.keys(share).forEach(key => {
|
|
const val = share[key];
|
|
if (typeof val === 'string' && val.length > 0) {
|
|
// If already absolute URL, leave it
|
|
if (/^https?:\/\//i.test(val)) return;
|
|
|
|
// Only prefix relative paths that start with '/'
|
|
if (val.startsWith('/')) {
|
|
// Avoid double slashes
|
|
share[key] = FRONTEND_URL ? `${FRONTEND_URL}${val}` : val;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
} catch (err) {
|
|
// In case of unexpected structure, return cloned original
|
|
console.error('addFrontendUrlToShareLinks error:', err);
|
|
return cloned;
|
|
}
|
|
|
|
return cloned;
|
|
}
|
|
|
|
module.exports = {
|
|
addFrontendUrlToShareLinks,
|
|
};
|