Completed
Push — master ( 7c7ab7...45cb8f )
by Mathieu
19s queued 11s
created

server/src/Application/HumanResource/User/Command/CreateUserCommandHandler.ts   A

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 53
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 46
mnd 3
bc 3
fnc 1
dl 0
loc 53
bpm 3
cpm 4
noi 0
c 0
b 0
f 0
rs 10

1 Function

Rating   Name   Duplication   Size   Complexity  
A CreateUserCommandHandler.execute 0 28 4
1
import {CommandHandler} from '@nestjs/cqrs';
2
import {Inject} from '@nestjs/common';
3
import {CreateUserCommand} from './CreateUserCommand';
4
import {IUserRepository} from 'src/Domain/HumanResource/User/Repository/IUserRepository';
5
import {IPasswordEncoder} from 'src/Application/IPasswordEncoder';
6
import {User, UserRole} from 'src/Domain/HumanResource/User/User.entity';
7
import {IsEmailAlreadyExist} from 'src/Domain/HumanResource/User/Specification/IsEmailAlreadyExist';
8
import {EmailAlreadyExistException} from 'src/Domain/HumanResource/User/Exception/EmailAlreadyExistException';
9
import {IDateUtils} from 'src/Application/IDateUtils';
10
import {EntryDateMissingException} from 'src/Domain/HumanResource/User/Exception/EntryDateMissingException';
11
12
@CommandHandler(CreateUserCommand)
13
export class CreateUserCommandHandler {
14
  constructor(
15
    @Inject('IUserRepository')
16
    private readonly userRepository: IUserRepository,
17
    @Inject('IPasswordEncoder')
18
    private readonly passwordEncoder: IPasswordEncoder,
19
    @Inject('IDateUtils')
20
    private readonly dateUtils: IDateUtils,
21
    private readonly isEmailAlreadyExist: IsEmailAlreadyExist
22
  ) {}
23
24
  public async execute(command: CreateUserCommand): Promise<string> {
25
    const {firstName, lastName, password, entryDate, role} = command;
26
    const email = command.email.toLowerCase();
27
28
    if (true === (await this.isEmailAlreadyExist.isSatisfiedBy(email))) {
29
      throw new EmailAlreadyExistException();
30
    }
31
32
    if (role !== UserRole.ACCOUNTANT && !entryDate) {
33
      throw new EntryDateMissingException();
34
    }
35
36
    const hashPassword = await this.passwordEncoder.hash(password);
37
    const apiToken = await this.passwordEncoder.hash(email + password);
38
    const user = await this.userRepository.save(
39
      new User(
40
        firstName,
41
        lastName,
42
        email,
43
        apiToken,
44
        hashPassword,
45
        role,
46
        entryDate ? this.dateUtils.format(entryDate, 'y-MM-dd') : null
47
      )
48
    );
49
50
    return user.getId();
51
  }
52
}
53