"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.validate = validate;
exports.stripErrors = stripErrors;

var _lodash = _interopRequireDefault(require("lodash"));

function validate(validatorsMap) {
  return new Promise(function (resolve, reject) {
    var result = Promise.resolve();
    var errors = {}; // iterate by all keys except null values

    _lodash.default.forOwn(_lodash.default.omitBy(validatorsMap, _lodash.default.isNull), function (validator, key) {
      result = result.then(function () {
        return validator.catch(function (error) {
          errors[key] = error;
          return Promise.resolve();
        });
      });
    });

    result.then(function () {
      if (_lodash.default.isEmpty(errors)) {
        resolve();
      } else {
        reject(errors); //FIXME Promise rejected with non-Error
      }
    });
  });
}

function stripErrors(errors) {
  return _lodash.default.reduce(errors, function (acc, errorDetails, errorFieldName) {
    if (_lodash.default.isString(errorDetails.message)) {
      acc[errorFieldName] = errorDetails.message;
    } else {
      acc[errorFieldName] = stripErrors(errorDetails);
    }

    return acc;
  }, {});
}