Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 1 | import xhrInterceptors from './xhrInterceptors.json5'; |
| 2 | |
| 3 | export {xhrInterceptors}; |
| 4 | |
| 5 | export function matchInterceptors(interceptFilter, url) { |
| 6 | return xhrInterceptors.interceptors.filter(interceptor => { |
| 7 | var regex = new RegExp(interceptor.urlRegex); |
| 8 | return interceptor.intercepts == interceptFilter && regex.test(url); |
| 9 | }); |
| 10 | } |
| 11 | |
| 12 | export function getResponseJSON(xhr) { |
| 13 | if (xhr.responseType === 'arraybuffer') { |
| 14 | var arrBuffer = xhr.response; |
| 15 | if (!arrBuffer) { |
| 16 | console.error('No array buffer.'); |
| 17 | return undefined; |
| 18 | } |
| 19 | var byteArray = new Uint8Array(arrBuffer); |
| 20 | var dec = new TextDecoder('utf-8'); |
| 21 | var rawResponse = dec.decode(byteArray); |
| 22 | return JSON.parse(rawResponse); |
| 23 | } |
| 24 | if (xhr.responseType === 'text' || xhr.responseType === '') |
| 25 | return JSON.parse(xhr.responseText); |
| 26 | if (xhr.responseType === 'json') return xhr.response; |
| 27 | |
| 28 | console.error( |
| 29 | 'Unexpected responseType ' + xhr.responseType + '. Request url: ', |
| 30 | xhr.$TWPTRequestURL); |
| 31 | return undefined; |
| 32 | } |
| 33 | |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 34 | export function triggerEvent(eventName, body, id) { |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 35 | var evt = new CustomEvent('TWPT_' + eventName, { |
| 36 | detail: { |
| 37 | body, |
avm99963 | 1f50f6f | 2021-08-12 23:04:41 +0200 | [diff] [blame] | 38 | id, |
Adrià Vilanova Martínez | 43ec2b9 | 2021-07-16 18:44:54 +0200 | [diff] [blame] | 39 | } |
| 40 | }); |
| 41 | window.dispatchEvent(evt); |
| 42 | } |