All files / src check-unique.js

96.55% Statements 28/29
78.57% Branches 11/14
100% Functions 4/4
96% Lines 24/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  1x 1x 1x   1x   1x       44x 44x 44x 44x   44x 52x     44x 44x 44x 44x 44x 44x   44x               44x   44x 28x 36x   28x         16x    
 
const errors = require('@feathersjs/errors');
const isNullsy = require('./helpers/is-nullsy');
const makeDebug = require('debug');
 
const debug = makeDebug('authLocalMgnt:checkUnique');
 
module.exports = checkUnique;
 
// This module is usually called from the UI to check username, email, etc. are unique.
async function checkUnique (options, identifyUser, ownId, meta, params = {}) {
  debug('checkUnique', identifyUser, ownId, meta);
  const usersService = options.app.service(options.service);
  const usersServiceIdName = usersService.id;
  const allProps = [];
 
  const keys = Object.keys(identifyUser).filter(
    key => !isNullsy(identifyUser[key])
  );
 
  try {
    for (let i = 0, ilen = keys.length; i < ilen; i++) {
      const prop = keys[i];
      const users = await usersService.find({ ...params, query: { [prop]: identifyUser[prop].trim() } });
      const items = Array.isArray(users) ? users : users.data;
      const isNotUnique = items.length > 1 ||
        (items.length === 1 && items[0][usersServiceIdName] !== ownId);
      allProps.push(isNotUnique ? prop : null);
    }
  } catch (err) {
    throw new errors.BadRequest(meta.noErrMsg ? null : 'checkUnique unexpected error.',
      { errors: { msg: err.message, $className: 'unexpected' } }
    );
  }
 
  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 }
    );
  }
 
  return null;
}