1
|
|
|
import {Inject} from '@nestjs/common'; |
2
|
|
|
import {CommandHandler} from '@nestjs/cqrs'; |
3
|
|
|
import {Customer} from 'src/Domain/Customer/Customer.entity'; |
4
|
|
|
import {CreateCustomerCommand} from './CreateCustomerCommand'; |
5
|
|
|
import {ICustomerRepository} from 'src/Domain/Customer/Repository/ICustomerRepository'; |
6
|
|
|
import {CustomerAlreadyExistException} from 'src/Domain/Customer/Exception/CustomerAlreadyExistException'; |
7
|
|
|
import {IsCustomerAlreadyExist} from 'src/Domain/Customer/Specification/IsCustomerAlreadyExist'; |
8
|
|
|
import {IAddressRepository} from 'src/Domain/Customer/Repository/IAddressRepository'; |
9
|
|
|
import {Address} from 'src/Domain/Customer/Address.entity'; |
10
|
|
|
|
11
|
|
|
@CommandHandler(CreateCustomerCommand) |
12
|
|
|
export class CreateCustomerCommandHandler { |
13
|
|
|
constructor( |
14
|
|
|
@Inject('ICustomerRepository') |
15
|
|
|
private readonly customerRepository: ICustomerRepository, |
16
|
|
|
@Inject('IAddressRepository') |
17
|
|
|
private readonly addressRepository: IAddressRepository, |
18
|
|
|
private readonly isCustomerAlreadyExist: IsCustomerAlreadyExist |
19
|
|
|
) {} |
20
|
|
|
|
21
|
|
|
public async execute(command: CreateCustomerCommand): Promise<string> { |
22
|
|
|
const {name, street, city, country, zipCode} = command; |
23
|
|
|
|
24
|
|
|
if (true === (await this.isCustomerAlreadyExist.isSatisfiedBy(name))) { |
25
|
|
|
throw new CustomerAlreadyExistException(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
const address = await this.addressRepository.save( |
29
|
|
|
new Address(street, city, zipCode, country) |
30
|
|
|
); |
31
|
|
|
|
32
|
|
|
const customer = await this.customerRepository.save( |
33
|
|
|
new Customer(name, address) |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
return customer.getId(); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|