| 1 |
/** |
| 2 |
* Optimole API Module |
| 3 |
* Handles communication with the REST API |
| 4 |
*/ |
| 5 |
|
| 6 |
import { optmlLogger } from './logger.js'; |
| 7 |
import { optmlStorage } from './storage.js'; |
| 8 |
|
| 9 |
/** |
| 10 |
* API communication utilities |
| 11 |
*/ |
| 12 |
export const optmlApi = { |
| 13 |
/** |
| 14 |
* Send data to the REST API using sendBeacon with fetch fallback |
| 15 |
* @param {Object} data - Data to send to the API |
| 16 |
*/ |
| 17 |
sendToRestApi: function(data) { |
| 18 |
// Use object destructuring for repeated property access |
| 19 |
const { restUrl } = window.optimoleDataOptimizer || {}; |
| 20 |
|
| 21 |
if (!restUrl) { |
| 22 |
optmlLogger.error('REST API URL not available'); |
| 23 |
return; |
| 24 |
} |
| 25 |
|
| 26 |
const endpoint = restUrl + '/optimizations'; |
| 27 |
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' }); |
| 28 |
|
| 29 |
// Use sendBeacon to send the data |
| 30 |
const success = navigator.sendBeacon(endpoint, blob); |
| 31 |
|
| 32 |
if (success) { |
| 33 |
optmlLogger.info('Data sent successfully using sendBeacon'); |
| 34 |
optmlStorage.markProcessed(data.u, data.d); |
| 35 |
} else { |
| 36 |
optmlLogger.error('Failed to send data using sendBeacon'); |
| 37 |
|
| 38 |
// Fallback to fetch if sendBeacon fails |
| 39 |
this._sendWithFetch(endpoint, data); |
| 40 |
} |
| 41 |
}, |
| 42 |
|
| 43 |
/** |
| 44 |
* Fallback method to send data using fetch |
| 45 |
* @private |
| 46 |
* @param {string} endpoint - API endpoint URL |
| 47 |
* @param {Object} data - Data to send |
| 48 |
*/ |
| 49 |
_sendWithFetch: function(endpoint, data) { |
| 50 |
fetch(endpoint, { |
| 51 |
method: 'POST', |
| 52 |
headers: { |
| 53 |
'Content-Type': 'application/json', |
| 54 |
}, |
| 55 |
body: JSON.stringify(data) |
| 56 |
}) |
| 57 |
.then(response => { |
| 58 |
if (!response.ok) throw new Error('Network response was not ok'); |
| 59 |
return response.json(); |
| 60 |
}) |
| 61 |
.then(responseData => { |
| 62 |
optmlLogger.info('Data sent successfully using fetch fallback:', responseData); |
| 63 |
optmlStorage.markProcessed(data.u, data.d); |
| 64 |
}) |
| 65 |
.catch(error => { |
| 66 |
optmlLogger.error('Error sending data using fetch fallback:', error); |
| 67 |
}); |
| 68 |
} |
| 69 |
}; |
| 70 |
|