fetcher.js
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/* global ajaxurl */
/**
* External dependencies
*/
import assign from 'lodash/assign';
/**
* Wrapper function for ajax calls to WordPress.
*
* @since 3.12.0
*/
function SmushFetcher() {
/**
* Request ajax with a promise.
* Use FormData Object as data if you need to upload file
*
* @param {string} action
* @param {Object|FormData} data
* @param {string} method
* @return {Promise<any>} Request results.
*/
function request(action, data = {}, method = 'POST') {
const args = {
url: ajaxurl,
method,
cache: false
};
if (data instanceof FormData) {
data.append('action', action);
data.append('_ajax_nonce', window.wp_smush_msgs.nonce);
args.contentType = false;
args.processData = false;
} else {
data._ajax_nonce = data._ajax_nonce || window.wp_smush_msgs.nonce;
data.action = action;
}
args.data = data;
return new Promise((resolve, reject) => {
jQuery.ajax(args).done(resolve).fail(reject);
}).then((response) => {
if (typeof response !== 'object') {
response = JSON.parse(response);
}
return response;
}).catch((error) => {
console.error('Error:', error);
});
}
const methods = {
/**
* Manage ajax for background.
*/
background: {
/**
* Start background process.
*/
start: () => {
return request('bulk_smush_start');
},
/**
* Cancel background process.
*/
cancel: () => {
return request('bulk_smush_cancel');
},
/**
* Initial State - Get stats on the first time.
*/
initState: () => {
return request('bulk_smush_get_status');
},
/**
* Get stats.
*/
getStatus: () => {
return request('bulk_smush_get_status');
},
getStats: () => {
return request('bulk_smush_get_global_stats');
}
},
smush: {
/**
* Sync stats.
*/
syncStats: ( data ) => {
data = data || {};
return request('get_stats', data);
},
/**
* Ignore All.
*/
ignoreAll: ( type ) => {
return request('wp_smush_ignore_all_failed_items', {
type: type,
});
},
},
/**
* Manage ajax for other requests
*/
common: {
/**
* Dismiss Notice.
*
* @param {string} dismissId Notification id.
*/
dismissNotice: (dismissId) => {
return request('smush_dismiss_notice', {
key: dismissId
});
},
/**
* Hide the new features modal.
*
* @param {string} modalID Notification id.
*/
hideModal: (modalID) => request('hide_modal', {
modal_id: modalID,
}),
/**
* Custom request.
*
* @param {Object} data
*/
request: (data) => data.action && request(data.action, data),
},
};
assign(this, methods);
}
const SmushAjax = new SmushFetcher();
export default SmushAjax;