-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathBaseModel.ts
99 lines (80 loc) · 2.3 KB
/
BaseModel.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import * as shortid from 'shortid';
import { Field, ID, Int, InterfaceType, ObjectType } from 'type-graphql';
import {
BeforeInsert,
Column,
CreateDateColumn,
PrimaryColumn,
PrimaryGeneratedColumn,
UpdateDateColumn,
VersionColumn
} from 'typeorm';
import { IDType } from './types';
// This interface adds all of the base type-graphql fields to our BaseClass
@InterfaceType()
export abstract class BaseGraphQLObject {
@Field(() => ID)
id!: IDType;
@Field() createdAt!: Date;
@Field() createdById?: IDType;
@Field({ nullable: true })
updatedAt?: Date;
@Field({ nullable: true })
updatedById?: IDType;
@Field({ nullable: true })
deletedAt?: Date;
@Field({ nullable: true })
deletedById?: IDType;
@Field(() => Int)
version!: number;
}
// This class adds all of the TypeORM decorators needed to create the DB table
@ObjectType({ implements: BaseGraphQLObject })
export abstract class BaseModel implements BaseGraphQLObject {
@PrimaryColumn({ type: String })
id!: IDType;
@CreateDateColumn() createdAt!: Date;
@Column() createdById!: IDType;
@UpdateDateColumn({ nullable: true })
updatedAt?: Date;
@Column({ nullable: true })
updatedById?: IDType;
@Column({ nullable: true })
deletedAt?: Date;
@Column({ nullable: true })
deletedById?: IDType;
@VersionColumn() version!: number;
getId() {
// If settings allow ID to be specified on create, use the specified ID
return this.id || shortid.generate();
}
// V3: DateTime should use getter to return ISO8601 string
getValue(field: any) {
const self = this as any;
if (self[field] instanceof Date) {
return self[field].toISOString();
}
return self[field];
}
@BeforeInsert()
setId() {
this.id = this.getId();
}
}
// This class adds all of the TypeORM decorators needed to create the DB table
@ObjectType({ implements: BaseGraphQLObject })
export abstract class BaseModelUUID implements BaseGraphQLObject {
@PrimaryGeneratedColumn('uuid')
id!: IDType;
@CreateDateColumn() createdAt!: Date;
@Column() createdById!: IDType;
@UpdateDateColumn({ nullable: true })
updatedAt?: Date;
@Column({ nullable: true })
updatedById?: IDType;
@Column({ nullable: true })
deletedAt?: Date;
@Column({ nullable: true })
deletedById?: IDType;
@VersionColumn() version!: number;
}