all files / lib/ responseListener.js

88% Statements 22/25
72.22% Branches 13/18
100% Functions 5/5
88% Lines 22/25
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                                                                          
var parseResponse = require("./parseResponse");
 
/**
 * @summary triggers existing listeners based on state of XMLHttpRequest.
 * @param xhr
 * @param {object} c - configuration object
 */
module.exports = function(xhr, c) {
    "use strict";
    var resp;
 
    switch (xhr.readyState) {
        case 1: {
            Eif (c.onOpen.length) {
                c.onOpen.forEach(function(cb) {
                    cb(xhr);
                });
            }
            break;
        }
        case 2: {
            Eif (c.onHeaders.length) {
                c.onHeaders.forEach(function(cb) {
                    cb(xhr);
                });
            }
            break;
        }
        case 4: {
            // dispatch to callbacks
            if (c.onSuccess.length && /2|3/.test(xhr.status.toString().charAt(0))) {
                try {
                    resp = parseResponse(xhr.response, c.responseType);
                } catch (e) {
                    if (e instanceof SyntaxError) {
                        throw new SyntaxError("unable to parse response of type: " + c.responseType + " for\n" + xhr.response);
                    } else {
                        throw Error(e);
                    }
                }
 
                // SUCCESS
                c.onSuccess.forEach(function(cb) {
                    cb(xhr, resp);
                });
            } else Eif (c.onFailure.length && /4|5/.test(xhr.status.toString().charAt(0))) {
                // FAILURE
                c.onFailure.forEach(function(cb) {
                    cb(xhr);
                });
            }
            break;
        }
        default: {
            break;
        }
    }
};