PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / vendor / team-updraft / lib-onboarding-wizard / Wizard / Onboarding / src / utils / api.js

api.js in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 4.7.0, at vendor/team-updraft/lib-onboarding-wizard/Wizard/Onboarding/src/utils/api.js

175 lines 5.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import apiFetch from '@wordpress/api-fetch';
2 import {glue} from './glue';
3
4 /**
5 * Generic API handler for onboarding actions
6 * @param {string} action - The action to perform
7 * @param {Object} data - Data to send with the request
8 * @returns {Promise<*>}
9 */
10
11 export const handleRequest = async( args ) => {
12 const {method, path, data} = args;
13
14 if ( method === 'GET' ) {
15 args.path = `${args.path}${glue(args.path)}${buildQueryString( args.data )}`;
16 delete args.data;
17 }
18 return apiFetch( args )
19 .then( ( response ) => {
20 if ( ! response.request_success ) {
21 throw new Error( 'invalid data error' );
22 }
23 if ( response.code ) {
24 throw new Error( response.message );
25 }
26 delete response.request_success;
27 return response;
28 })
29 .catch( ( error ) => {
30 // If REST API fails, try AJAX request
31 return ajaxRequest( method, path, data ).catch( () => {
32 // If AJAX also fails, generate error
33 console.log( error.message, args.path );
34 throw error;
35 });
36 });
37 }
38
39 export const updateAction = async( data = {}, action ) => {
40 const onboardingData = window[`teamupdraft_onboarding`] || {}
41 const endpointUrl = onboardingData.prefix + '/v1/onboarding/do_action/'+action;
42 data.nonce = onboardingData.nonce;
43 const path = endpointUrl;
44 const method = 'POST';
45
46 let args = {
47 path,
48 method,
49 data,
50 };
51
52 return await handleRequest(args);
53 }
54
55 const siteUrl = ( ) => {
56 const onboardingData = window[`teamupdraft_onboarding`] || {}
57 let url = onboardingData.admin_ajax_url;
58
59 if ( 'https:' === window.location.protocol && -1 === url.indexOf( 'https://' ) ) {
60 return url.replace( 'http://', 'https://' );
61 }
62 return url;
63 };
64
65 const ajaxRequest = async( method, path, requestData = null ) => {
66 //if requestData is an object, convert it to an array
67 const queryString = buildQueryString( requestData );
68 //add path to request data
69 requestData.path = path;
70 const url = 'GET' === method ? `${siteUrl()}&rest_action=${path.replace( '?', '&' )}&`+queryString : siteUrl();
71 const options = {
72 method,
73 headers: { 'Content-Type': 'application/json; charset=UTF-8' }
74 };
75
76 if ( 'POST' === method ) {
77
78 options.body = JSON.stringify({ path, data: requestData } );
79 }
80 try {
81 const response = await fetch( url, options );
82 if ( ! response.ok ) {
83 return Promise.reject( new Error( 'AJAX request failed' ) );
84 }
85
86 const responseData = await response.json();
87 if (
88 ! responseData.data ||
89 ! Object.prototype.hasOwnProperty.call( responseData.data, 'request_success' )
90 ) {
91 return Promise.reject( new Error( 'AJAX request failed' ) );
92 }
93
94 delete responseData.data.request_success;
95
96 // return promise with the data object
97 return Promise.resolve( responseData.data );
98 } catch ( error ) {
99 return Promise.reject( new Error( 'AJAX request failed' ) );
100 }
101 }
102
103 /**
104 * Build query string from object of parameters
105 * @param {Object} params
106 * @returns {string}
107 */
108 const buildQueryString = ( params ) => {
109 return Object.keys( params )
110 .filter( ( key ) => params[key] !== undefined && null !== params[key])
111 .map( ( key ) => {
112 const value = serializeValue( params[key]);
113 if ( Array.isArray( value ) ) {
114
115 // Handle arrays by using the PHP array syntax: metrics[]=value1&metrics[]=value2
116 return value
117 .map( ( v ) => `${encodeURIComponent( key )}[]=${encodeURIComponent( v )}` )
118 .join( '&' );
119 }
120 return `${encodeURIComponent( key )}=${encodeURIComponent( value )}`;
121 })
122 .join( '&' );
123 };
124
125 /**
126 * Serialize value for URL parameters, handling arrays and objects
127 * @param {*} value - Value to serialize
128 * @returns {string} Serialized value
129 */
130 const serializeValue = ( value ) => {
131 if ( Array.isArray( value ) ) {
132
133 // For arrays, add [] to the key and keep values separate
134 return value;
135 }
136 if ( 'object' === typeof value && null !== value ) {
137 return JSON.stringify( value );
138 }
139 return value;
140 };
141
142
143 /**
144 * Send Admin Ajax for default wordpress ajax requests
145 * @param {Object} params
146 * @returns {Promise<*>}
147 */
148 export const adminAjaxRequest = async(requestData = null ) => {
149 const method = 'POST';
150 const fullUrl = new URL(siteUrl());
151 fullUrl.search = ""; // remove query parameters
152 const url = fullUrl.toString();
153 // Convert object to x-www-form-urlencoded string
154 const formBody = new URLSearchParams(requestData).toString();
155
156 const options = {
157 method,
158 headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
159 body: formBody
160 };
161
162 try {
163 const response = await fetch( url, options );
164 if ( !response.ok ) {
165 return Promise.reject( new Error( 'AJAX request failed' ) );
166 }
167
168 const responseData = await response.json();
169
170 // return promise with the data object
171 return Promise.resolve( responseData );
172 } catch ( error ) {
173 return Promise.reject( new Error( 'AJAX request failed' ) );
174 }
175 }