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