All files set_request.js

73.08% Statements 19/26
25% Branches 1/4
66.67% Functions 8/12
76% Lines 19/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 60 61 62                    4x 1x     4x 1x         3x 3x             1x             12x 12x 12x 12x 12x 12x   12x               1x 1x     1x 1x       12x    
import {isFunction} from 'lodash';
 
import checkStatus from './check_status';
import errorFn from './create_error';
import parseData from './parse';
import progressFn from './set_progress';
import successFn from './create_success';
import readyState from './ready_state';
 
function addError(xhr, err){
  xhr.addEventListener('error', function(evt){
    err(`Network Error: ${evt.error.message}`);
  });
 
  xhr.addEventListener('abort', function(evt){
    err(`Network Abort: ${evt.error.message}`);
  });
}
 
function addProgress(xhr, prog){
  let check_prog = progressFn(prog);
  xhr.addEventListener('progress', function(evt){
    check_prog(evt.loaded, evt.total, evt.lengthComputable);
  });
}
 
function addReadyState(xhr, stateChange){
  // console.log()
  xhr.addEventListener('readystatechange', function(){
    stateChange(xhr);
  });
}
 
export default function(resolve, reject){
  let err, stateChange, suc;
  const xhr = new XMLHttpRequest();
  err = errorFn(reject, parseData);
  suc = successFn(resolve, parseData);
  stateChange = readyState(suc, err, checkStatus);
  addError(xhr, err);
  addReadyState(xhr, stateChange);
 
  const obj = {
    progress: function(prog){
      if (!isFunction(prog)) return obj;
      addProgress(xhr, prog);
      return obj;
    }
    , get: ()=>xhr
    , open: function(state, url){
      xhr.open(state, url, true);
      return obj;
    }
    , send: function(send){
      let data = (send) ? JSON.stringify(send) : null;
      xhr.send(data);
    }
  };
 
  return obj;
};