|
1 | 1 | import { ObjectId } from "bson"; |
2 | 2 | import type { AtLeast } from "../types/mod.ts"; |
3 | 3 |
|
| 4 | +/** |
| 5 | + * Base entity parameters for all database entities. |
| 6 | + */ |
4 | 7 | export interface IBase<Kind extends string> { |
| 8 | + /** Typescript annotation for permissioning/authorization purposes. */ |
5 | 9 | readonly kind: Kind; |
6 | | - __v?: number; |
| 10 | + /** Entity version stored in the database. */ |
| 11 | + _version?: number; |
| 12 | + /** Entity identifier stored in the database. */ |
7 | 13 | _id: ObjectId; |
| 14 | + /** Entity created date. */ |
8 | 15 | createdAt: Date; |
| 16 | + /** Entity unpdated date. */ |
9 | 17 | updatedAt: Date; |
| 18 | + /** Entity created by {@link User} id. */ |
10 | 19 | createdBy: ObjectId; |
| 20 | + /** Entity updated by {@link User} id. */ |
11 | 21 | updatedBy: ObjectId; |
12 | 22 | } |
13 | 23 |
|
14 | 24 | export class Base<K extends string> { |
15 | | - readonly __v: IBase<K>["__v"]; |
| 25 | + readonly _version: IBase<K>["_version"]; |
16 | 26 | readonly _id: IBase<K>["_id"]; |
17 | | - readonly createdAt: Date; |
18 | | - readonly updatedAt: Date; |
19 | | - readonly createdBy: ObjectId; |
20 | | - readonly updatedBy: ObjectId; |
| 27 | + readonly createdAt: IBase<K>["createdAt"]; |
| 28 | + readonly updatedAt: IBase<K>["updatedAt"]; |
| 29 | + readonly createdBy: IBase<K>["createdBy"]; |
| 30 | + readonly updatedBy: IBase<K>["updatedBy"]; |
21 | 31 |
|
22 | 32 | constructor({ |
23 | 33 | createdAt, |
24 | 34 | updatedAt, |
25 | 35 | createdBy, |
26 | 36 | updatedBy, |
27 | 37 | _id, |
28 | | - __v, |
| 38 | + _version = 0, |
29 | 39 | }: AtLeast<IBase<K>, "createdBy">) { |
30 | | - this.__v = __v; |
| 40 | + this._version = _version; |
31 | 41 | this._id = _id || new ObjectId(); |
32 | 42 |
|
33 | | - const now = new Date(Date.now()); |
| 43 | + const now = new Date(); |
34 | 44 | this.createdAt = createdAt || now; |
35 | 45 | this.updatedAt = updatedAt || now; |
36 | 46 |
|
37 | 47 | this.createdBy = createdBy; |
38 | 48 | this.updatedBy = updatedBy || createdBy; |
39 | 49 | } |
40 | 50 |
|
| 51 | + /** |
| 52 | + * Transforms the base class object into a json object. Useful for saving the entity to the database. |
| 53 | + * @returns a json representation of the base entity. |
| 54 | + */ |
41 | 55 | toJSON(): Omit<IBase<K>, "kind"> { |
42 | 56 | return { |
43 | | - __v: this.__v, |
| 57 | + _version: this._version, |
44 | 58 | _id: this._id, |
45 | 59 | createdAt: this.createdAt, |
46 | 60 | updatedAt: this.updatedAt, |
|
0 commit comments