| 1 |
/** |
| 2 |
* Yatra API Helper |
| 3 |
* Handles API endpoint URL construction based on WordPress permalink structure |
| 4 |
*/ |
| 5 |
|
| 6 |
window.YatraApiHelper = { |
| 7 |
/** |
| 8 |
* Get the correct API URL based on WordPress permalink structure |
| 9 |
* @param {string} endpoint - The API endpoint (e.g., '/downloads/1869/download-url') |
| 10 |
* @returns {string} The full API URL |
| 11 |
*/ |
| 12 |
getApiUrl(endpoint) { |
| 13 |
// Check if WordPress uses pretty permalinks |
| 14 |
const currentUrl = window.location.href; |
| 15 |
const usesPrettyPermalinks = this.detectPrettyPermalinks(currentUrl); |
| 16 |
|
| 17 |
if (window.yatraConfig?.debug) { |
| 18 |
console.log('Yatra API Helper - Using permalinks:', usesPrettyPermalinks ? 'Pretty' : 'Plain'); |
| 19 |
} |
| 20 |
|
| 21 |
if (usesPrettyPermalinks) { |
| 22 |
return `/wp-json/yatra/v1${endpoint}`; |
| 23 |
} else { |
| 24 |
return `/index.php?rest_route=/yatra/v1${endpoint}`; |
| 25 |
} |
| 26 |
}, |
| 27 |
|
| 28 |
/** |
| 29 |
* Detect if WordPress uses pretty permalinks |
| 30 |
* @param {string} url - Current page URL |
| 31 |
* @returns {boolean} True if pretty permalinks are detected |
| 32 |
*/ |
| 33 |
detectPrettyPermalinks(url) { |
| 34 |
// Method 1: Use WordPress provided data (most reliable) |
| 35 |
const yatraData = window.yatraTripData || window.yatraBookingData || {}; |
| 36 |
if (yatraData.permalinkStructure !== undefined) { |
| 37 |
const isPlain = yatraData.permalinkStructure === 'plain'; |
| 38 |
if (window.yatraConfig?.debug) { |
| 39 |
console.log('Yatra API Helper - WordPress permalink structure:', yatraData.permalinkStructure, 'isPlain:', isPlain); |
| 40 |
} |
| 41 |
return !isPlain; // Return true if NOT plain (i.e., pretty) |
| 42 |
} |
| 43 |
|
| 44 |
// Method 2: Check WordPress REST API settings |
| 45 |
const wpApiSettings = window.wpApiSettings || {}; |
| 46 |
if (wpApiSettings.root) { |
| 47 |
// If root ends with /wp-json/, pretty permalinks are working |
| 48 |
const usesPretty = wpApiSettings.root.includes('/wp-json/'); |
| 49 |
if (window.yatraConfig?.debug) { |
| 50 |
console.log('Yatra API Helper - WP API settings root:', wpApiSettings.root, 'usesPretty:', usesPretty); |
| 51 |
} |
| 52 |
return usesPretty; |
| 53 |
} |
| 54 |
|
| 55 |
// Method 3: Check current URL structure |
| 56 |
const hasPrettyStructure = |
| 57 |
url.includes('/trip/') || // Trip URLs |
| 58 |
url.includes('/category/') || // Category URLs |
| 59 |
url.includes('/tag/') || // Tag URLs |
| 60 |
(url.includes('/') && !url.includes('?') && !url.includes('=')); |
| 61 |
|
| 62 |
if (window.yatraConfig?.debug) { |
| 63 |
console.log('Yatra API Helper - URL structure analysis:', hasPrettyStructure); |
| 64 |
} |
| 65 |
|
| 66 |
// Method 4: Default to plain since we know pretty permalinks aren't working |
| 67 |
if (window.yatraConfig?.debug) { |
| 68 |
console.log('Yatra API Helper - Defaulting to plain permalinks (fallback)'); |
| 69 |
} |
| 70 |
return false; |
| 71 |
}, |
| 72 |
|
| 73 |
/** |
| 74 |
* Get WordPress nonce from available sources |
| 75 |
* @returns {string} WordPress nonce |
| 76 |
*/ |
| 77 |
getNonce() { |
| 78 |
// Try multiple sources for the nonce |
| 79 |
const sources = [ |
| 80 |
window.yatraTripData?.nonce, |
| 81 |
window.yatraBookingData?.nonce, |
| 82 |
window.yatraVars?.nonce, |
| 83 |
window.wpApiSettings?.nonce, |
| 84 |
window.yatraConfig?.nonce |
| 85 |
]; |
| 86 |
|
| 87 |
// Return the first available nonce |
| 88 |
for (const nonce of sources) { |
| 89 |
if (nonce && nonce !== '') { |
| 90 |
if (window.yatraConfig?.debug) { |
| 91 |
console.log('Yatra API Helper - Using nonce from source:', sources.indexOf(nonce)); |
| 92 |
} |
| 93 |
return nonce; |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
if (window.yatraConfig?.debug) { |
| 98 |
console.warn('Yatra API Helper - No nonce found, API requests may fail'); |
| 99 |
} |
| 100 |
return ''; |
| 101 |
}, |
| 102 |
|
| 103 |
/** |
| 104 |
* Make API request with automatic URL handling |
| 105 |
* @param {string} endpoint - API endpoint |
| 106 |
* @param {Object} options - Fetch options |
| 107 |
* @returns {Promise} Fetch promise |
| 108 |
*/ |
| 109 |
async apiRequest(endpoint, options = {}) { |
| 110 |
const url = this.getApiUrl(endpoint); |
| 111 |
|
| 112 |
// Only add nonce for authenticated requests or when user is logged in |
| 113 |
const nonce = this.shouldUseNonce() ? this.getNonce() : null; |
| 114 |
|
| 115 |
const defaultOptions = { |
| 116 |
method: 'GET', |
| 117 |
headers: { |
| 118 |
'Content-Type': 'application/json', |
| 119 |
...(nonce && { 'X-WP-Nonce': nonce }) |
| 120 |
} |
| 121 |
}; |
| 122 |
|
| 123 |
const fetchOptions = { ...defaultOptions, ...options }; |
| 124 |
|
| 125 |
try { |
| 126 |
const response = await fetch(url, fetchOptions); |
| 127 |
return response; |
| 128 |
} catch (error) { |
| 129 |
console.error('API request failed:', error); |
| 130 |
throw error; |
| 131 |
} |
| 132 |
}, |
| 133 |
|
| 134 |
/** |
| 135 |
* Determine if nonce should be used for the request |
| 136 |
* @returns {boolean} Whether to use nonce |
| 137 |
*/ |
| 138 |
shouldUseNonce() { |
| 139 |
// Check if user is logged in (WordPress sets this in the body class) |
| 140 |
const body = document.body; |
| 141 |
const isLoggedIn = body && body.classList.contains('logged-in'); |
| 142 |
|
| 143 |
// Also check if we have user data indicating logged in status |
| 144 |
const hasUserData = window.yatraTripData?.userId || window.yatraBookingData?.userId; |
| 145 |
|
| 146 |
const shouldUse = isLoggedIn || hasUserData; |
| 147 |
if (window.yatraConfig?.debug) { |
| 148 |
console.log('Yatra API Helper - User logged in:', shouldUse); |
| 149 |
} |
| 150 |
return shouldUse; |
| 151 |
}, |
| 152 |
|
| 153 |
/** |
| 154 |
* Get download URL for a specific download ID |
| 155 |
* @param {number} downloadId - Download ID |
| 156 |
* @param {number} bookingId - Optional booking ID |
| 157 |
* @returns {Promise} API response |
| 158 |
*/ |
| 159 |
getDownloadUrl(downloadId, bookingId = 0) { |
| 160 |
let endpoint = `/downloads/${downloadId}/download-url`; |
| 161 |
if (bookingId > 0) { |
| 162 |
endpoint += `?booking_id=${bookingId}`; |
| 163 |
} |
| 164 |
return this.apiRequest(endpoint); |
| 165 |
}, |
| 166 |
|
| 167 |
/** |
| 168 |
* Get download file info |
| 169 |
* @param {number} downloadId - Download ID |
| 170 |
* @returns {Promise} API response |
| 171 |
*/ |
| 172 |
getDownloadInfo(downloadId) { |
| 173 |
return this.apiRequest(`/downloads/${downloadId}/download`); |
| 174 |
} |
| 175 |
}; |
| 176 |
|
| 177 |
// Auto-initialize when DOM is ready |
| 178 |
document.addEventListener('DOMContentLoaded', function() { |
| 179 |
// API Helper is ready for use |
| 180 |
// Debug logging can be enabled by setting window.yatraConfig.debug = true |
| 181 |
if (window.yatraConfig?.debug) { |
| 182 |
console.log('Yatra API Helper - Initialized'); |
| 183 |
const detectedStructure = window.YatraApiHelper.detectPrettyPermalinks(window.location.href); |
| 184 |
console.log('Yatra API Helper - Permalink structure:', detectedStructure ? 'Pretty' : 'Plain'); |
| 185 |
} |
| 186 |
}); |
| 187 |
|