forked from Sairyss/domain-driven-hexagon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
address.value-object.ts
47 lines (41 loc) · 1.36 KB
/
address.value-object.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
import { ValueObject } from '@libs/ddd';
import { Guard } from '@libs/guard';
import { ArgumentOutOfRangeException } from '@libs/exceptions';
/** Note:
* Value Objects with multiple properties can contain
* other Value Objects inside if needed.
* */
export interface AddressProps {
country: string;
postalCode: string;
street: string;
}
export class Address extends ValueObject<AddressProps> {
get country(): string {
return this.props.country;
}
get postalCode(): string {
return this.props.postalCode;
}
get street(): string {
return this.props.street;
}
/**
* Note: This is a very simplified example of validation,
* real world projects will have stricter rules.
* You can avoid this type of validation here and validate
* only on the edge of the application (in controllers when receiving
* a request) sacrificing some security for performance and convenience.
*/
protected validate(props: AddressProps): void {
if (!Guard.lengthIsBetween(props.country, 2, 50)) {
throw new ArgumentOutOfRangeException('country is out of range');
}
if (!Guard.lengthIsBetween(props.street, 2, 50)) {
throw new ArgumentOutOfRangeException('street is out of range');
}
if (!Guard.lengthIsBetween(props.postalCode, 2, 10)) {
throw new ArgumentOutOfRangeException('postalCode is out of range');
}
}
}