PluginProbe
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization / 4.2.8
Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization v4.2.8
4.2.13 4.2.12 4.2.11 4.2.10 4.2.9 4.2.8 4.2.7 4.2.6 4.2.5 2.5.5 2.5.6 2.5.7 3.0.0 3.0.1 3.1.0 3.1.1 3.1.2 3.1.3 3.10.0 3.11.0 3.11.1 3.11.2 3.11.3 3.12.0 3.12.1 All 134 releases
optimole-wp / assets / js / modules / api.js

api.js in Optimole – Optimize Images | Convert WebP & AVIF | CDN & Lazy Load | Image Optimization 4.2.8, at assets/js/modules/api.js

70 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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