All files / src/utils UserUtils.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 1/1
100% Lines 15/15

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 268x     8x   4x 4x 2x   2x 2x 2x 3x 5x 5x   5x 2x     3x   2x      
import { Commun, SecurityUtils } from '@commun/core'
import { UserModel } from '..'
 
export const UserUtils = {
  async generateUniqueUsername (prefix: string) {
    let user = await Commun.getEntityDao<UserModel>('users').findOne({ username: prefix })
    if (!user) {
      return prefix
    }
    let chars = 1
    let username = prefix
    while (user) {
      for (let i = 0; i < 3; i++) {
        username = `${prefix}-${SecurityUtils.generateRandomString(chars)}`
        user = await Commun.getEntityDao<UserModel>('users')
          .findOne({ username })
        if (!user) {
          break
        }
      }
      chars++
    }
    return username
  }
}