
import feathersErrors from 'feathers-errors';

import getItems from './get-items';

const errors = feathersErrors.errors;

export default function (schema, ajvOrAjv, options = { allErrors: true }) {
  const addNewError = options.addNewError || addNewErrorDflt;
  delete options.addNewError;
  // TODO: Any better way to tell if ajvOrAjv is an instance or a constructor?
  let ajv, Ajv;
  if (typeof ajvOrAjv.addKeyword !== 'function') {
    Ajv = ajvOrAjv;
    ajv = new Ajv(options);
  } else {
    ajv = ajvOrAjv;
  }
  const validate = ajv.compile(schema); // for fastest execution

  return hook => {
    const items = getItems(hook);
    const itemsArray = Array.isArray(items) ? items : [items];
    const itemsLen = itemsArray.length;
    let errorMessages = null;
    let invalid = false;

    return Promise.all(itemsArray.map((item, index) => {
      return Promise.resolve(validate(item))
        // Handler for synchronous validation
        .then((isValid) => {
          if (!isValid) {
            // eslint-disable-next-line prefer-promise-reject-errors
            return Promise.reject({errors: validate.errors});
          }
        })
        .catch((err) => {
          invalid = true;

          err.errors.forEach(ajvError => {
            errorMessages = addNewError(errorMessages, ajvError, itemsLen, index);
          });
        });
    })).then(() => {
      if (invalid) {
        throw new errors.BadRequest('Invalid schema', { errors: errorMessages });
      }
    });
  };
}

function addNewErrorDflt (errorMessages, ajvError, itemsLen, index) {
  const leader = itemsLen === 1 ? '' : `in row ${index + 1} of ${itemsLen}, `;
  let message;

  if (ajvError.dataPath) {
    message = `'${leader}${ajvError.dataPath.substring(1)}' ${ajvError.message}`;
  } else {
    message = `${leader}${ajvError.message}`;
    if (ajvError.params && ajvError.params.additionalProperty) {
      message += `: '${ajvError.params.additionalProperty}'`;
    }
  }

  return (errorMessages || []).concat(message);
}

@@ -1043,64 +1043,30 @@
     
-// eslint-disable-next-line prefer-p
+return P
 romise
--
+.
 reject
--errors
+(
 %0D%0A  
@@ -1079,39 +1079,46 @@
     
-return Promise.reject(%7Be
+  new ajv.constructor.ValidationE
 rror
-s: 
+(
 vali
@@ -1128,17 +1128,17 @@
 e.errors
-%7D
+)
 );%0D%0A    
@@ -1177,32 +1177,111 @@
 tch((err) =%3E %7B%0D%0A
+          if (!(err instanceof ajv.constructor.ValidationError)) throw err;%0D%0A%0D%0A
           invali

Improve validateSchema error handling