forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet.entity.ts
50 lines (42 loc) · 1.38 KB
/
wallet.entity.ts
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
import { ArgumentOutOfRangeException } from '@libs/exceptions';
import { AggregateRoot } from '@libs/ddd/domain/base-classes/aggregate-root.base';
import { UUID } from '@libs/ddd/domain/value-objects/uuid.value-object';
import { Err, Ok, Result } from 'oxide.ts/dist';
import { WalletNotEnoughBalanceError } from '../../errors/wallet.errors';
export interface CreateWalletProps {
userId: UUID;
}
export interface WalletProps extends CreateWalletProps {
balance: number;
}
export class WalletEntity extends AggregateRoot<WalletProps> {
protected readonly _id: UUID;
static create(create: CreateWalletProps): WalletEntity {
const id = UUID.generate();
const props: WalletProps = { ...create, balance: 0 };
const wallet = new WalletEntity({ id, props });
return wallet;
}
deposit(amount: number): void {
this.props.balance += amount;
}
withdraw(amount: number): Result<null, WalletNotEnoughBalanceError> {
if (this.props.balance - amount < 0) {
return Err(new WalletNotEnoughBalanceError());
}
this.props.balance -= amount;
return Ok(null);
}
/**
* Protects wallet invariant.
* This method is executed by a repository
* before saving entity in a database.
*/
public validate(): void {
if (this.props.balance < 0) {
throw new ArgumentOutOfRangeException(
'Wallet balance cannot be less than 0',
);
}
}
}