-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
wallet.entity.ts
55 lines (46 loc) · 1.5 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
51
52
53
54
55
import { AggregateID, AggregateRoot } from '@libs/ddd';
import { ArgumentOutOfRangeException } from '@libs/exceptions';
import { Err, Ok, Result } from 'oxide.ts';
import { WalletCreatedDomainEvent } from './events/wallet-created.domain-event';
import { WalletNotEnoughBalanceError } from './wallet.errors';
import { randomUUID } from 'crypto';
export interface CreateWalletProps {
userId: AggregateID;
}
export interface WalletProps extends CreateWalletProps {
balance: number;
}
export class WalletEntity extends AggregateRoot<WalletProps> {
protected readonly _id: AggregateID;
static create(create: CreateWalletProps): WalletEntity {
const id = randomUUID();
const props: WalletProps = { ...create, balance: 0 };
const wallet = new WalletEntity({ id, props });
wallet.addEvent(
new WalletCreatedDomainEvent({ aggregateId: id, userId: create.userId }),
);
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',
);
}
}
}