All files / src/methods check-unique.ts

96.77% Statements 30/31
82.35% Branches 14/17
100% Functions 4/4
96.3% Lines 26/27

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 50 51 52 53 54 55 56 57 58 59 60 61 62 631x 1x 1x               1x         1x           44x   44x 44x   44x 44x 44x   44x 52x     44x 44x 44x 44x 44x 44x   44x               44x   44x 28x 36x   28x         16x    
import { BadRequest } from '@feathersjs/errors';
import isNullsy from '../helpers/is-nullsy';
import makeDebug from 'debug';
 
import type { Id } from '@feathersjs/feathers';
import type {
  CheckUniqueOptions,
  IdentifyUser
} from '../types';
 
const debug = makeDebug('authLocalMgnt:checkUnique');
 
/**
 * This module is usually called from the UI to check username, email, etc. are unique.
 */
export default async function checkUnique (
  options: CheckUniqueOptions,
  identifyUser: IdentifyUser,
  ownId?: Id,
  meta?: { noErrMsg?: boolean}
): Promise<null> {
  debug('checkUnique', identifyUser, ownId, meta);
 
  ownId = ownId || null;
  meta = 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({ 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 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 BadRequest(meta.noErrMsg ? null : 'Values already taken.',
      { errors: errs }
    );
  }
 
  return null;
}