blob: 909549bf77e62a009e48d2eeade3d4ad9436dad1 [file] [log] [blame]
Adrià Vilanova Martínez102d54b2022-12-18 11:12:11 +01001import {correctArrayKeys} from '../common/protojs';
2
3import xhrInterceptors from './interceptors.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 getResponseText(xhr, transformArrayPb = true) {
15 let response;
16 if (xhr.responseType === 'arraybuffer') {
17 var arrBuffer = xhr.response;
18 if (!arrBuffer) {
19 console.error('No array buffer.');
20 return undefined;
21 }
22 let byteArray = new Uint8Array(arrBuffer);
23 let dec = new TextDecoder('utf-8');
24 response = dec.decode(byteArray);
25 } else if (xhr.responseType === 'text' || xhr.responseType === '') {
26 response = xhr.responseText;
27 } else if (xhr.responseType === 'json') {
28 response = JSON.stringify(xhr.response);
29 } else {
30 console.error(
31 'Unexpected responseType ' + xhr.responseType + '. Request url: ',
32 xhr.$TWPTRequestURL);
33 return undefined;
34 }
35
36 if (xhr.$isArrayProto && transformArrayPb)
37 response = correctArrayKeys(response);
38
39 return response;
40}
41
42export function getResponseJSON(xhr) {
43 let response;
44 if (xhr.responseType === 'arraybuffer') {
45 var arrBuffer = xhr.response;
46 if (!arrBuffer) {
47 console.error('No array buffer.');
48 return undefined;
49 }
50 let byteArray = new Uint8Array(arrBuffer);
51 let dec = new TextDecoder('utf-8');
52 let rawResponse = dec.decode(byteArray);
53 response = JSON.parse(rawResponse);
54 } else if (xhr.responseType === 'text' || xhr.responseType === '') {
55 response = JSON.parse(xhr.responseText);
56 } else if (xhr.responseType === 'json') {
57 response = xhr.response;
58 } else {
59 console.error(
60 'Unexpected responseType ' + xhr.responseType + '. Request url: ',
61 xhr.$TWPTRequestURL);
62 return undefined;
63 }
64
65 if (xhr.$isArrayProto) response = correctArrayKeys(response);
66 return response;
67}
68
69export function triggerEvent(eventName, body, id) {
70 var evt = new CustomEvent('TWPT_' + eventName, {
71 detail: {
72 body,
73 id,
74 }
75 });
76 window.dispatchEvent(evt);
77}