| 1 |
export default { |
| 2 |
call( endpoint, method = 'GET', body = false ) { |
| 3 |
let nonce = wpupg_admin.api_nonce; |
| 4 |
|
| 5 |
if ( 'object' === typeof window.wpApiSettings && window.wpApiSettings.nonce ) { |
| 6 |
nonce = window.wpApiSettings.nonce; |
| 7 |
} |
| 8 |
|
| 9 |
let args = { |
| 10 |
method, |
| 11 |
headers: { |
| 12 |
'X-WP-Nonce': nonce, |
| 13 |
'Accept': 'application/json', |
| 14 |
'Content-Type': 'application/json', |
| 15 |
// Don't cache API calls. |
| 16 |
'Cache-Control': 'no-cache, no-store, must-revalidate', |
| 17 |
'Pragma': 'no-cache', |
| 18 |
'Expires': 0, |
| 19 |
}, |
| 20 |
credentials: 'same-origin', |
| 21 |
}; |
| 22 |
|
| 23 |
// Use POST for PUT and DELETE and emulate for better compatibility. |
| 24 |
if ( 'PUT' === method || 'DELETE' === method ) { |
| 25 |
args.method = 'POST'; |
| 26 |
args.headers['X-HTTP-Method-Override'] = method; |
| 27 |
} |
| 28 |
|
| 29 |
// Add optional body data. |
| 30 |
if ( body ) { |
| 31 |
args.body = JSON.stringify(body); |
| 32 |
} |
| 33 |
|
| 34 |
return fetch(endpoint, args).then(function (response) { |
| 35 |
if ( response.ok ) { |
| 36 |
return response.json(); |
| 37 |
} else { |
| 38 |
// Log errors in console and try to get as much debug information as possible. |
| 39 |
console.log(endpoint, args); |
| 40 |
console.log(response); |
| 41 |
const message = "Something went wrong. Using a firewall like Cloudflare or Sucuri? Try whitelisting your IP. If that doesn't work, please contact support@bootstrapped.ventures with the following details:"; |
| 42 |
const responseDetails = `${response.url} ${response.redirected ? '(redirected)' : ''}- ${response.status} - ${response.statusText}`; |
| 43 |
|
| 44 |
try { |
| 45 |
response.text().then(text => { |
| 46 |
console.log(text); |
| 47 |
alert( `${message}\r\n\r\n${responseDetails}\r\n\r\n${text}` ); |
| 48 |
}) |
| 49 |
} catch(e) { |
| 50 |
console.log(e); |
| 51 |
alert( `${message}\r\n\r\n${responseDetails}\r\n\r\n${e}` ); |
| 52 |
} |
| 53 |
|
| 54 |
return false; |
| 55 |
} |
| 56 |
}); |
| 57 |
}, |
| 58 |
}; |
| 59 |
|