All files / src/helpers get-user-data.ts

95% Statements 19/20
91.43% Branches 32/35
100% Functions 1/1
95% Lines 19/20

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x             1x       339x 339x 33x           306x 306x   306x             306x       12x           294x         16x           278x       9x           269x       16x           253x       9x           244x    
import { BadRequest } from '@feathersjs/errors';
 
import type {
  UsersArrayOrPaginated,
  User
} from '../types';
 
export default function getUserData (
  data: UsersArrayOrPaginated,
  fieldsToChecks?: string[]
): User {
  fieldsToChecks ??= [];
  if (Array.isArray(data) ? data.length === 0 : data.total === 0) {
    throw new BadRequest(
      'User not found.',
      { errors: { $className: 'badParams' } }
    );
  }
 
  const users = Array.isArray(data) ? data : data.data;
  const user = users[0];
 
  Iif (users.length !== 1) {
    throw new BadRequest(
      'More than 1 user selected.',
      { errors: { $className: 'badParams' } }
    );
  }
 
  if (
    fieldsToChecks.includes('isNotVerified') &&
    user.isVerified
  ) {
    throw new BadRequest(
      'User is already verified.',
      { errors: { $className: 'isNotVerified' } }
    );
  }
 
  if (
    fieldsToChecks.includes('isNotVerifiedOrHasVerifyChanges') &&
    user.isVerified &&
    !Object.keys(user.verifyChanges || {}).length
  ) {
    throw new BadRequest(
      'User is already verified & not awaiting changes.',
      { errors: { $className: 'nothingToVerify' } }
    );
  }
 
  if (
    fieldsToChecks.includes('isVerified') &&
    !user.isVerified
  ) {
    throw new BadRequest(
      'User is not verified.',
      { errors: { $className: 'isVerified' } }
    );
  }
 
  if (
    fieldsToChecks.includes('verifyNotExpired') &&
    user.verifyExpires < Date.now()
  ) {
    throw new BadRequest(
      'Verification token has expired.',
      { errors: { $className: 'verifyExpired' } }
    );
  }
 
  if (
    fieldsToChecks.includes('resetNotExpired') &&
    user.resetExpires < Date.now()
  ) {
    throw new BadRequest(
      'Password reset token has expired.',
      { errors: { $className: 'resetExpired' } }
    );
  }
 
  return user;
}