all files / src/core/ request.js

58.82% Statements 10/17
42.86% Branches 6/14
66.67% Functions 2/3
58.82% Lines 10/17
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                                                             
function get(options) {
 
    var xhr = new XMLHttpRequest();
 
    xhr.open('get', options.url);
    // With response type set browser can get and put binary data
    // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data
    // Default is text, and it can be set
    // arraybuffer, blob, document, json, text
    xhr.responseType = options.responseType || 'text';
 
    Iif (options.onprogress) {
        //https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
        xhr.onprogress = function(e) {
            if (e.lengthComputable) {
                var percent = e.loaded / e.total;
                options.onprogress(percent, e.loaded, e.total);
            }
            else {
                options.onprogress(null);
            }
        };
    }
    xhr.onload = function(e) {
        Iif (xhr.status >= 400) {
            options.onerror && options.onerror();
        }
        else {
            options.onload && options.onload(xhr.response);
        }
    };
    Iif (options.onerror) {
        xhr.onerror = options.onerror;
    }
    xhr.send(null);
}
 
export default {
    get : get
};