blob: 867c32334bf0499b4d5328f9a3387f15eeb66835 [file] [log] [blame]
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +02001import xhrInterceptors from './xhrInterceptors.json5';
2
3export {xhrInterceptors};
4
5export 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
12export 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
avm999631f50f6f2021-08-12 23:04:41 +020034export function triggerEvent(eventName, body, id) {
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020035 var evt = new CustomEvent('TWPT_' + eventName, {
36 detail: {
37 body,
avm999631f50f6f2021-08-12 23:04:41 +020038 id,
Adrià Vilanova Martínez43ec2b92021-07-16 18:44:54 +020039 }
40 });
41 window.dispatchEvent(evt);
42}