all files / app/components/errorsMapper/ errorsHelper.service.js

100% Statements 18/18
87.5% Branches 7/8
100% Functions 6/6
100% Lines 18/18
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                          103×                                         102×                           102× 12× 12× 10× 10×     12×                           102×                      
/**
 * @ngdoc service
 * @name app.components.errorsHelper
 * @description
 * Adds error processing to a controller
 *
 */
(function () {
  'use strict';
 
  angular
    .module('app.components')
    .factory('errorsHelper', factory);
 
  /** @ngInject */
  function factory(errorsMapper) {
    return activate;
 
    /**
     * @ngdoc function
     * @name activate
     * @methodOf app.components.errorsHelper
     * @description
     * Adds members to a controller:
     * * errorsOfResponse()
     * * clearErrors()
     *
     * @param {Object} _vm_
     * Controller instance
     * @param {Object} errorsMap
     * Options to identify how errors should be handled:
     * * names
     * * map
     *
     * See {@link app.components.errorsMapper errorsMapper}.
     */
    function activate(_vm_, errorsMap) {
      // Initialize controller
      var vm = _vm_;
      /**
       * @ngdoc function
       * @name errorsOfResponse
       * @methodOf app.components.errorsHelper
       * @description
       * Categorize error messages from an HTTP response
       *
       * @param {Object} response
       * HTTP response
       * @returns {Object}
       * Hash of categorized error messages created by
       * {@link app.components.errorsMapper errorsMapper}
       */
      vm.errorsOfResponse = function (response) {
        var result;
        if (angular.isObject(response.data)) {
          var data = response.data;
          result = errorsMapper(data, errorsMap.names, errorsMap.map);
        }
        else
          result = errorsMapper({'errors': response.statusText ? response.statusText : 'Unexpected error'});
        return result;
      };
      /**
       * @ngdoc function
       * @name clearErrors
       * @methodOf app.components.errorsHelper
       * @description
       * Clear categories of errors.
       *
       * @param {Object} errors
       * Categories arrays
       * @param {Array} names
       * Names of categories to clear
       */
      vm.clearErrors = function(errors, names) {
        if (errors) {
          angular.forEach(names, function (name) {
            Eif (errors[name])
              errors[name] = null;
          });
        }
      };
    }
  }
})();