All files / src/lib xhr.ts

82.76% Statements 24/29
53.13% Branches 17/32
66.67% Functions 2/3
82.76% Lines 24/29

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 551x                   1x 3x 3x     3x 3x 3x 3x 3x         3x 3x 3x 3x 2x 2x 2x         1x         3x 3x 3x 6x 6x       3x       3x    
const NOOP = function (): void { /* Noop */ };
interface XHROpts {
    url: string;
    type: 'GET' | 'POST';
    success?: Function;
    fail?: Function;
    withCredentials: boolean;
    header?: any;
    data?: any;
}
export default function (opts: XHROpts): XMLHttpRequest {
    const useXDomainRequest: boolean = 'XDomainRequest' in window;
    const req = useXDomainRequest
        ? new (window as any).XDomainRequest()
        : new XMLHttpRequest();
    req.open(opts.type || 'GET', opts.url, true);
    req.success = opts.success || NOOP;
    req.fail = opts.fail || NOOP;
    req.withCredentials = !!opts.withCredentials;
    Iif (useXDomainRequest) {
        req.onload = opts.success || NOOP;
        req.onerror = opts.fail || NOOP;
        req.onprogress = NOOP;
    } else {
        req.onreadystatechange = function (): void {
            Eif (req.readyState == 4) {
                const status = req.status;
                if (status >= 200) {
                    try {
                        const response = JSON.parse(req.responseText);
                        opts.success && opts.success(response);
                    } catch (e) {
                        opts.fail && opts.fail(e);
                    }
                } else {
                    opts.fail && opts.fail(req.statusText);
                }
            }
        };
    }
    Eif (opts.type === 'POST') {
        Eif (opts.header && !useXDomainRequest) {
            for (const key in opts.header) {
                Eif (key in opts.header) {
                    req.setRequestHeader(key, opts.header[key]);
                }
            }
        }
        req.send(opts.data);
    } else {
        req.send();
    }
    return req;
}