All files checkUniqueness.js

95.45% Statements 21/22
100% Branches 13/13
88.89% Functions 8/9
94.74% Lines 18/19
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      1x 1x     1x 44x 44x 44x   44x 52x   44x 44x   44x 44x     44x             44x   44x 28x 36x   28x            
 
/* eslint-env node */
 
const errors = require('feathers-errors');
const debug = require('debug')('authManagement:checkUniqueness');
 
// This module is usually called from the UI to check username, email, etc. are unique.
module.exports = function checkUniqueness (options, identifyUser, ownId, meta) {
  debug('checkUniqueness', identifyUser, ownId, meta);
  const users = options.app.service(options.service);
  const usersIdName = users.id;
 
  const keys = Object.keys(identifyUser).filter(
    key => identifyUser[key] !== undefined && identifyUser[key] !== null);
 
  return Promise.all(
    keys.map(prop => users.find({ query: { [prop]: identifyUser[prop].trim() } })
      .then(data => {
        const items = Array.isArray(data) ? data : data.data;
        const isNotUnique = items.length > 1 ||
          (items.length === 1 && items[0][usersIdName] !== ownId);
 
        return isNotUnique ? prop : null;
      })
    ))
    .catch(err => {
      throw new errors.GeneralError(err);
    })
    .then(allProps => {
      const errProps = allProps.filter(prop => prop);
 
      if (errProps.length) {
        const errs = {};
        errProps.forEach(prop => { errs[prop] = 'Already taken.'; });
 
        throw new errors.BadRequest(meta.noErrMsg ? null : 'Values already taken.',
          { errors: errs }
        );
      }
    });
};