| 1 |
import axios from 'axios' |
| 2 |
import { Sentry } from '@onboarding/hooks/useSentry' |
| 3 |
|
| 4 |
const Axios = axios.create({ |
| 5 |
baseURL: window.extOnbData.root, |
| 6 |
headers: { |
| 7 |
'X-WP-Nonce': window.extOnbData.nonce, |
| 8 |
'X-Requested-With': 'XMLHttpRequest', |
| 9 |
'X-Extendify-Onboarding': true, |
| 10 |
'X-Extendify': true, |
| 11 |
}, |
| 12 |
}) |
| 13 |
|
| 14 |
Axios.interceptors.request.use( |
| 15 |
(request) => checkDevMode(startPerformance(request)), |
| 16 |
(error) => error, |
| 17 |
) |
| 18 |
Axios.interceptors.response.use( |
| 19 |
(response) => findResponse(measurePerformance(response)), |
| 20 |
(error) => handleErrors(error), |
| 21 |
) |
| 22 |
|
| 23 |
const findResponse = (response) => { |
| 24 |
return Object.prototype.hasOwnProperty.call(response, 'data') |
| 25 |
? response.data |
| 26 |
: response |
| 27 |
} |
| 28 |
|
| 29 |
const handleErrors = (error) => { |
| 30 |
if (!error.response) { |
| 31 |
return |
| 32 |
} |
| 33 |
Sentry.captureException(error) |
| 34 |
console.error(error.response) |
| 35 |
return Promise.reject(findResponse(error.response)) |
| 36 |
} |
| 37 |
|
| 38 |
const checkDevMode = (request) => { |
| 39 |
request.headers['X-Extendify-Onboarding-Dev-Mode'] = |
| 40 |
window.location.search.indexOf('DEVMODE') > -1 |
| 41 |
request.headers['X-Extendify-Onboarding-Local-Mode'] = |
| 42 |
window.location.search.indexOf('LOCALMODE') > -1 |
| 43 |
return request |
| 44 |
} |
| 45 |
|
| 46 |
const startPerformance = (request) => { |
| 47 |
try { |
| 48 |
const endpoint = request?.url?.split('/')?.pop() |
| 49 |
if (!endpoint) return request |
| 50 |
performance.mark(`${endpoint}-extendify`) |
| 51 |
} catch (e) { |
| 52 |
// do nothing |
| 53 |
} |
| 54 |
return request |
| 55 |
} |
| 56 |
const measurePerformance = (response) => { |
| 57 |
try { |
| 58 |
const url = new URL(response?.request?.responseURL) |
| 59 |
const endpoint = url.pathname?.split('/')?.pop() |
| 60 |
if (!endpoint) return response |
| 61 |
const time = performance.measure(`${endpoint}-extendify`, { |
| 62 |
start: `${endpoint}-extendify`, |
| 63 |
detail: { |
| 64 |
context: { type: 'request' }, |
| 65 |
extendify: true, |
| 66 |
}, |
| 67 |
}) |
| 68 |
const q = new URLSearchParams(window.location.search) |
| 69 |
if (q?.has('performance')) { |
| 70 |
console.info( |
| 71 |
`~> Endpoint /${endpoint} ${ |
| 72 |
// special case to show the site type being queried |
| 73 |
endpoint === 'styles' |
| 74 |
? `(${url.searchParams.get('siteType')}) ` |
| 75 |
: '' |
| 76 |
}in ${time.duration.toFixed()}ms`, |
| 77 |
) |
| 78 |
} |
| 79 |
} catch (e) { |
| 80 |
// do nothing |
| 81 |
} |
| 82 |
return response |
| 83 |
} |
| 84 |
|
| 85 |
export { Axios } |
| 86 |
|