Passed
Pull Request — develop (#7)
by Tito
02:17
created

Entity.serialize   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 1
1
import { FieldNotFoundError } from "Errors/Entities/FieldNotFoundError";
2
import { UniqueEntityId } from "Utilities/Ids/UniqueEntityId";
3
4
/**
5
 * Abstract Entity class
6
 */
7
export abstract class Entity<T> {
8
  /**
9
   * Id of the entity
10
   */
11
  protected readonly _id: UniqueEntityId;
12
13
  /**
14
   * Collection of properties
15
   */
16
  protected readonly props: T;
17
18
  /**
19
   * @param T props
20
   * @param IEntityDefinition definition Needed for each specific entity overriding this entity.  The child entity should not expose this parameter in its own constructor
21
   * @param UniqueEntityId id If not sent, it generates a UUID
22
   */
23
  constructor(props: T, id?: UniqueEntityId) {
24
    this.props = props;
25
    this._id =
26
      typeof props["id"] !== "undefined" && props["id"] !== null
27
        ? new UniqueEntityId(props["id"])
28
        : id
29
        ? id
30
        : new UniqueEntityId();
31
  }
32
33
  /**
34
   * Gets the id in its natural type
35
   *
36
   * @returns string|number
37
   */
38
  public getId(): string | number {
39
    return this._id.toValue();
40
  }
41
42
  /**
43
   * Gets the id stringified
44
   *
45
   * @returns string
46
   */
47
  public getIdString(): string {
48
    return this._id.toString();
49
  }
50
51
  /**
52
   * Field getter
53
   *
54
   * @param field
55
   *
56
   * @throws FieldNotFoundError
57
   */
58
  public get(field: string): any {
59
    if (typeof this.props[field] === "undefined") {
60
      throw new FieldNotFoundError(field);
61
    }
62
63
    return this.props[field];
64
  }
65
66
  /**
67
   * Serialize the entity as a JSON
68
   *
69
   * @returns object
70
   */
71
  public serialize(): object {
72
    return {
73
      id: this._id.toValue(),
74
      ...this.props,
75
    };
76
  }
77
}
78