blob: baa2bd308d2a1e2425e59a36bd744d85a79604f4 [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
34export function triggerEvent(eventName, body) {
35 var evt = new CustomEvent('TWPT_' + eventName, {
36 detail: {
37 body,
38 }
39 });
40 window.dispatchEvent(evt);
41}