-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
WrappedEntity.ts
199 lines (156 loc) · 6.67 KB
/
WrappedEntity.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { inspect } from 'util';
import type { EntityManager } from '../EntityManager';
import type {
AnyEntity, ConnectionType, Dictionary, EntityData, EntityDictionary, EntityMetadata, IHydrator, EntityValue, EntityKey,
IWrappedEntityInternal, Populate, PopulateOptions, Primary, AutoPath, Loaded, Ref, AddEager, Loaded, LoadedReference, EntityDTO,
} from '../typings';
import { Reference } from './Reference';
import { EntityTransformer } from '../serialization/EntityTransformer';
import type { AssignOptions } from './EntityAssigner';
import { EntityAssigner } from './EntityAssigner';
import type { EntityLoaderOptions } from './EntityLoader';
import { Utils } from '../utils/Utils';
import type { LockMode } from '../enums';
import { ValidationError } from '../errors';
import type { EntityIdentifier } from './EntityIdentifier';
import { helper } from './wrap';
import type { SerializationContext } from '../serialization/SerializationContext';
export class WrappedEntity<Entity extends object> {
__initialized = true;
__touched = false;
__populated?: boolean;
__lazyInitialized?: boolean;
__managed?: boolean;
__onLoadFired?: boolean;
__schema?: string;
__em?: EntityManager;
__serializationContext: { root?: SerializationContext<Entity>; populate?: PopulateOptions<Entity>[] } = {};
__loadedProperties = new Set<string>();
__loadedRelations = new Set<string>();
__data: Dictionary = {};
__processing = false;
/** stores last known primary key, as its current state might be broken due to propagation/orphan removal, but we need to know the PK to be able t remove the entity */
__pk?: Primary<Entity>;
/** holds the reference wrapper instance (if created), so we can maintain the identity on reference wrappers too */
__reference?: Reference<Entity>;
/** holds last entity data snapshot, so we can compute changes when persisting managed entities */
__originalEntityData?: EntityData<Entity>;
/** holds wrapped primary key, so we can compute change set without eager commit */
__identifier?: EntityIdentifier;
constructor(private readonly entity: Entity,
private readonly hydrator: IHydrator,
private readonly pkGetter?: (e: Entity) => Primary<Entity>,
private readonly pkSerializer?: (e: Entity) => string,
private readonly pkGetterConverted?: (e: Entity) => Primary<Entity>) { }
isInitialized(): boolean {
return this.__initialized;
}
isTouched(): boolean {
return this.__touched;
}
populated(populated = true): void {
this.__populated = populated;
this.__lazyInitialized = false;
}
toReference(): Ref<Entity> & LoadedReference<Loaded<Entity, AddEager<Entity>>> {
this.__reference ??= new Reference(this.entity);
return this.__reference as Ref<Entity> & LoadedReference<Loaded<Entity, AddEager<Entity>>>;
}
toObject<Ignored extends EntityKey<Entity> = never>(ignoreFields?: Ignored[]): Omit<EntityDTO<Entity>, Ignored> {
return EntityTransformer.toObject(this.entity, ignoreFields);
}
toPOJO(): EntityDTO<Entity> {
return EntityTransformer.toObject(this.entity, [], true);
}
toJSON(...args: any[]): EntityDictionary<Entity> {
// toJSON methods is added to the prototype during discovery to support automatic serialization via JSON.stringify()
return (this.entity as Dictionary).toJSON(...args);
}
assign(data: EntityData<Entity>, options?: AssignOptions): Entity {
if ('assign' in this.entity) {
return (this.entity as Dictionary).assign(data, options);
}
return EntityAssigner.assign(this.entity, data, options);
}
async init<P extends Populate<Entity> = Populate<Entity>>(populated = true, populate?: P, lockMode?: LockMode, connectionType?: ConnectionType): Promise<Entity> {
if (!this.__em) {
throw ValidationError.entityNotManaged(this.entity);
}
await this.__em.findOne(this.entity.constructor.name, this.entity, { refresh: true, lockMode, populate, connectionType, schema: this.__schema });
this.populated(populated);
this.__lazyInitialized = true;
return this.entity;
}
async populate<Hint extends string = never>(
populate: AutoPath<T, Hint>[] | boolean,
options: EntityLoaderOptions<T, Hint> = {},
): Promise<Loaded<T, Hint>> {
if (!this.__em) {
throw ValidationError.entityNotManaged(this.entity);
}
await this.__em.populate(this.entity, populate, options);
return this.entity as Loaded<T, Hint>;
}
hasPrimaryKey(): boolean {
const pk = this.getPrimaryKey();
return pk != null;
}
getPrimaryKey(convertCustomTypes = false): Primary<Entity> | null {
const prop = this.__meta.getPrimaryProps()[0];
if (this.__pk != null && this.__meta.compositePK) {
return Utils.getCompositeKeyValue(this.__pk, this.__meta, convertCustomTypes ? 'convertToDatabaseValue' : false, this.__platform);
}
if (convertCustomTypes && this.__pk != null && prop.customType) {
return prop.customType.convertToDatabaseValue(this.__pk, this.__platform);
}
if (convertCustomTypes) {
return this.__pk ?? this.pkGetterConverted!(this.entity);
}
return this.__pk ?? this.pkGetter!(this.entity);
}
// this method is currently used only in `Driver.syncCollection` and can be probably removed
getPrimaryKeys(convertCustomTypes = false): Primary<Entity>[] | null {
const pk = this.getPrimaryKey(convertCustomTypes);
if (pk == null) {
return null;
}
if (this.__meta.compositePK) {
return this.__meta.primaryKeys.reduce((ret, pk) => {
const child = this.entity[pk] as AnyEntity<Entity> | Primary<unknown>;
if (Utils.isEntity(child, true)) {
const childPk = helper(child).getPrimaryKeys(convertCustomTypes);
ret.push(...childPk as Primary<Entity>[]);
} else {
ret.push(child as Primary<Entity>);
}
return ret;
}, [] as Primary<Entity>[]);
}
return [pk];
}
getSchema(): string | undefined {
return this.__schema;
}
setSchema(schema?: string): void {
this.__schema = schema;
}
setPrimaryKey(id: Primary<Entity> | null) {
this.entity[this.__meta!.primaryKeys[0]] = id as EntityValue<Entity>;
this.__pk = id!;
}
getSerializedPrimaryKey(): string {
return this.pkSerializer!(this.entity);
}
get __meta(): EntityMetadata<Entity> {
return (this.entity as IWrappedEntityInternal<Entity>).__meta!;
}
get __platform() {
return (this.entity as IWrappedEntityInternal<Entity>).__platform!;
}
get __primaryKeys(): Primary<Entity>[] {
return Utils.getPrimaryKeyValues(this.entity, this.__meta!.primaryKeys) as Primary<Entity>[];
}
[inspect.custom]() {
return `[WrappedEntity<${this.__meta!.className}>]`;
}
}