All files / API index.js

66.07% Statements 37/56
58.82% Branches 30/51
75% Functions 6/8
66.07% Lines 37/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165      20x 20x   20x 20x   20x                   275x 275x                       275x 275x     275x   275x 208x   208x 208x 198x 198x     10x     67x       20x                                                                                     20x 10x 3x 3x   3x       3x             10x                                 10x     20x 67x                           20x 208x 1x     207x       207x 197x 10x 10x        
import getCookie from '../Helpers/getCookie';
 
// Regular expression patterns for testing content-type response headers.
const RE_CONTENT_TYPE_JSON = new RegExp("^application/(x-)?json", "i");
const RE_CONTENT_TYPE_TEXT = new RegExp("^text/", "i");
// Static strings.
const TYPE_JSON = 'application/json';
const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occurred while processing your request.";
 
export const client = async (
    endpoint,
    data = undefined,
    {
        headers: customHeaders,
        accept: accept = TYPE_JSON,
        type: type = TYPE_JSON,
        ...customConfig
    } = {}
) => {
    try {
        const config = {
            method: data ? 'POST' : 'GET',
            body: data ? JSON.stringify(data) : undefined,
            credentials: 'include',
            headers: {
                'Accept': accept ? accept : null,
                'Content-Type': data ? type : undefined,
                ...customHeaders
            },
            ...customConfig,
        }
 
        const csrfToken = getCookie('XSRF-TOKEN');
        Iif (csrfToken !== undefined) {
            config.headers['X-XSRF-TOKEN'] = csrfToken.replace('%3D', '=');
        }
        const url = `${window.location.origin.replace(/\/$/, "")}${endpoint}`;
 
        const fetchResponse = await fetch(url, config);
        const responseData = await unwrapResponseData(fetchResponse);
 
        return new Promise(async (resolve, reject) => {
            if (fetchResponse.ok && (fetchResponse.status >= 200 && fetchResponse.status < 300)) {
                fetchResponse.data = responseData;
                return resolve(fetchResponse);
            }
 
            return reject(normalizeError(responseData, url, config, fetchResponse));
        });
    } catch (error) {
        return Promise.reject(normalizeTransportError(error));
    }
}
 
export const mediaClient = async (
    endpoint,
    data = undefined,
    {
        headers: customHeaders,
        accept: accept = TYPE_JSON,
        ...customConfig
    } = {}
) => {
    try {
        const config = {
            method: data ? 'POST' : 'GET',
            body: data ? data : undefined,
            credentials: 'include',
            headers: {
                'Accept': accept ? accept : null,
                ...customHeaders
            },
            ...customConfig,
        }
 
        const csrfToken = getCookie('XSRF-TOKEN');
        if (csrfToken !== undefined) {
            config.headers['X-XSRF-TOKEN'] = csrfToken.replace('%3D', '=');
        }
        const url = `${window.location.origin.replace(/\/$/, "")}${endpoint}`;
 
        const fetchResponse = await fetch(url, config);
        const responseData = await unwrapResponseData(fetchResponse);
 
        return new Promise(async (resolve, reject) => {
            if (fetchResponse.ok && (fetchResponse.status >= 200 && fetchResponse.status < 300)) {
                fetchResponse.data = responseData;
                return resolve(fetchResponse);
            }
 
            return reject(normalizeError(responseData, url, config, fetchResponse));
        });
    } catch (error) {
        return Promise.reject(normalizeTransportError(error));
    }
}
 
const normalizeError = (data, url, config, fetchResponse) => {
    if (fetchResponse.status === 401 && window.location.pathname !== '/login') {
        new Promise(async (resolve, reject) => {
            try {
                // Only if we are not in a test environment (Jest)
                Iif (process.env.JEST_WORKER_ID === undefined || process.env.NODE_ENV !== 'test') {
                    localStorage.setItem('WA_Login', window.location.href);
                    window.location.replace(window.location.origin + '/login');
                }
                resolve(true);
            } catch (error) {
                return reject(error);
            }
        });
    }
 
    var error = {
        data: {
            type: "ServerError",
            message: UNEXPECTED_ERROR_MESSAGE,
            ...data
        },
        status: {
            code: fetchResponse.status,
            text: fetchResponse.statusText,
            isAbort: false,
        },
        // The following data is being provided for debugging
        requestUrl: url,
        requestConfig: config,
        response: fetchResponse,
    }
 
    return error;
}
 
const normalizeTransportError = transportError => {
    return ({
        data: {
            type: "TransportError",
            message: UNEXPECTED_ERROR_MESSAGE,
            rootCause: transportError
        },
        status: {
            code: 0,
            text: "Unknown",
            isAbort: (transportError.name === "AbortError")
        },
    });
}
 
const unwrapResponseData = async response => {
    if (response.status === 204) {
        return;
    }
 
    const contentType = response.headers.has('Content-Type')
        ? response.headers.get('Content-Type')
        : "";
 
    if (RE_CONTENT_TYPE_JSON.test(contentType)) {
        return await response.json();
    } else if (RE_CONTENT_TYPE_TEXT.test(contentType)) {
        return await response.text();
    } else E{
        return await response.blob();
    }
}