blob: 526296cf43d1bcd7b42eb4e0bb33a474253bec7f [file] [log] [blame]
Adrià Vilanova Martínez4e0cb182022-06-26 00:21:50 +02001import {correctArrayKeys} from '../common/protojs';
2
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +02003import xhrInterceptors from './xhrInterceptors.json5';
4
5export {xhrInterceptors};
6
7export 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
14export function getResponseJSON(xhr) {
Adrià Vilanova Martínez4e0cb182022-06-26 00:21:50 +020015 let response;
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020016 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ínez4e0cb182022-06-26 00:21:50 +020022 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ínez43ec2b92021-07-16 18:44:54 +020035 }
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020036
Adrià Vilanova Martínez4e0cb182022-06-26 00:21:50 +020037 if (xhr.$isArrayProto) response = correctArrayKeys(response);
38 return response;
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020039}
40
avm999631f50f6f2021-08-12 23:04:41 +020041export function triggerEvent(eventName, body, id) {
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020042 var evt = new CustomEvent('TWPT_' + eventName, {
43 detail: {
44 body,
avm999631f50f6f2021-08-12 23:04:41 +020045 id,
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020046 }
47 });
48 window.dispatchEvent(evt);
49}