/
EntityTransformer.ts
265 lines (203 loc) · 8.81 KB
/
EntityTransformer.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import type { Collection } from '../entity/Collection';
import type { AnyEntity, Dictionary, EntityDTO, EntityKey, EntityMetadata, EntityValue, IPrimaryKey } from '../typings';
import { helper, wrap } from '../entity/wrap';
import type { Platform } from '../platforms';
import { Utils } from '../utils/Utils';
import { ReferenceKind } from '../enums';
import type { Reference } from '../entity/Reference';
import { SerializationContext } from './SerializationContext';
import { RawQueryFragment } from '../utils/RawQueryFragment';
function isVisible<Entity extends object>(meta: EntityMetadata<Entity>, propName: EntityKey<Entity>, ignoreFields: string[] = []): boolean {
const prop = meta.properties[propName];
const visible = prop && !prop.hidden;
const prefixed = prop && !prop.primary && propName.startsWith('_'); // ignore prefixed properties, if it's not a PK
return visible && !prefixed && !ignoreFields.includes(propName);
}
export class EntityTransformer {
static toObject<Entity extends object, Ignored extends EntityKey<Entity> = never>(entity: Entity, ignoreFields: Ignored[] = [], raw = false): Omit<EntityDTO<Entity>, Ignored> {
if (!Array.isArray(ignoreFields)) {
ignoreFields = [];
}
const wrapped = helper(entity);
let contextCreated = false;
if (!wrapped.__serializationContext.root) {
const root = new SerializationContext<Entity>(
wrapped.__config,
wrapped.__serializationContext.populate,
wrapped.__serializationContext.fields,
wrapped.__serializationContext.exclude,
);
SerializationContext.propagate(root, entity, isVisible);
contextCreated = true;
}
const root = wrapped.__serializationContext.root!;
const meta = wrapped.__meta;
const ret = {} as Dictionary;
const keys = new Set<EntityKey<Entity>>();
if (meta.serializedPrimaryKey && !meta.compositePK) {
keys.add(meta.serializedPrimaryKey);
} else {
meta.primaryKeys.forEach(pk => keys.add(pk));
}
if (wrapped.isInitialized() || !wrapped.hasPrimaryKey()) {
Utils.keys(entity as object).forEach(prop => keys.add(prop));
}
const visited = root.visited.has(entity);
if (!visited) {
root.visited.add(entity);
}
[...keys]
.filter(prop => raw ? meta.properties[prop] : isVisible<Entity>(meta, prop, ignoreFields))
.map(prop => {
const populated = root.isMarkedAsPopulated(meta.className, prop);
const partiallyLoaded = root.isPartiallyLoaded(meta.className, prop);
const isPrimary = wrapped.__config.get('serialization').includePrimaryKeys && meta.properties[prop].primary;
if (!partiallyLoaded && !populated && !isPrimary) {
return [prop, undefined];
}
const cycle = root.visit(meta.className, prop);
if (cycle && visited) {
return [prop, undefined];
}
const val = EntityTransformer.processProperty<Entity>(prop, entity, raw, populated);
if (!cycle) {
root.leave(meta.className, prop);
}
if (val instanceof RawQueryFragment) {
throw new Error(`Trying to serialize raw SQL fragment: '${val.sql}'`);
}
return [prop, val] as const;
})
.filter(([, value]) => typeof value !== 'undefined')
.forEach(([prop, value]) => ret[this.propertyName(meta, prop!, wrapped.__platform, raw) as any] = value as any);
if (!visited) {
root.visited.delete(entity);
}
if (!wrapped.isInitialized() && wrapped.hasPrimaryKey()) {
return ret as EntityDTO<Entity>;
}
// decorated getters
meta.props
.filter(prop => prop.getter && prop.getterName === undefined && !prop.hidden && typeof entity[prop.name] !== 'undefined')
// @ts-ignore
.forEach(prop => ret[this.propertyName(meta, prop.name, wrapped.__platform, raw) as any] = this.processProperty(prop.name, entity, raw));
// decorated get methods
meta.props
.filter(prop => prop.getterName && !prop.hidden && entity[prop.getterName] instanceof Function)
// @ts-ignore
.forEach(prop => ret[this.propertyName(meta, prop.name, wrapped.__platform, raw)] = this.processProperty(prop.getterName as keyof Entity & string, entity, raw));
if (contextCreated) {
root.close();
}
return ret as EntityDTO<Entity>;
}
private static propertyName<Entity>(meta: EntityMetadata<Entity>, prop: EntityKey<Entity>, platform?: Platform, raw?: boolean): EntityKey<Entity> {
if (raw) {
return prop;
}
if (meta.properties[prop].serializedName) {
return meta.properties[prop].serializedName as EntityKey<Entity>;
}
if (meta.properties[prop].primary && platform) {
return platform.getSerializedPrimaryKeyField(prop) as EntityKey<Entity>;
}
return prop;
}
private static processProperty<Entity extends object>(prop: EntityKey<Entity>, entity: Entity, raw: boolean, populated: boolean): EntityValue<Entity> | undefined {
const wrapped = helper(entity);
const property = wrapped.__meta.properties[prop];
const serializer = property?.serializer;
const value = entity[prop];
// getter method
if (entity[prop] as unknown instanceof Function) {
const returnValue = (entity[prop] as unknown as () => Entity[keyof Entity & string])();
if (serializer && !raw) {
return serializer(returnValue);
}
return returnValue as EntityValue<Entity>;
}
if (serializer && !raw) {
return serializer(value);
}
if (Utils.isCollection(value)) {
return EntityTransformer.processCollection(prop, entity, raw, populated);
}
if (Utils.isEntity(value, true)) {
return EntityTransformer.processEntity(prop, entity, wrapped.__platform, raw, populated);
}
if (Utils.isScalarReference(value)) {
return value.unwrap();
}
if (property.kind === ReferenceKind.EMBEDDED) {
if (Array.isArray(value)) {
return (value as object[]).map(item => {
const wrapped = item && helper(item);
return wrapped ? wrapped.toJSON() : item;
}) as EntityValue<Entity>;
}
const wrapped = value && helper(value!);
return wrapped ? wrapped.toJSON() as EntityValue<Entity> : value;
}
const customType = property?.customType;
if (customType) {
return customType.toJSON(value, wrapped.__platform);
}
if (property?.primary) {
return wrapped.__platform.normalizePrimaryKey(value as unknown as IPrimaryKey) as unknown as EntityValue<Entity>;
}
return value;
}
private static processEntity<Entity extends object>(prop: keyof Entity, entity: Entity, platform: Platform, raw: boolean, populated: boolean): EntityValue<Entity> | undefined {
const child = entity[prop] as unknown as Entity | Reference<Entity>;
const wrapped = helper(child as Entity);
const meta = wrapped.__meta;
const visible = meta.primaryKeys.filter(prop => isVisible(meta, prop));
if (raw && wrapped.isInitialized() && child !== entity) {
return wrapped.toPOJO() as unknown as EntityValue<Entity>;
}
function isPopulated() {
if (wrapped.__populated != null) {
return wrapped.__populated;
}
if (populated) {
return true;
}
return !wrapped.__managed;
}
if (wrapped.isInitialized() && isPopulated() && child !== entity) {
return wrap(child).toJSON() as EntityValue<Entity>;
}
const pk = wrapped.getPrimaryKey(true)!;
if (wrapped.__config.get('serialization').forceObject) {
return Utils.primaryKeyToObject(meta, pk, visible) as EntityValue<Entity>;
}
if (Utils.isPlainObject(pk)) {
const pruned = Utils.primaryKeyToObject(meta, pk, visible) as EntityValue<Entity>;
if (visible.length === 1) {
return platform.normalizePrimaryKey(pruned[visible[0]] as IPrimaryKey) as EntityValue<Entity>;
}
return pruned;
}
return platform.normalizePrimaryKey(pk as IPrimaryKey) as EntityValue<Entity>;
}
private static processCollection<Entity extends object>(prop: keyof Entity, entity: Entity, raw: boolean, populated: boolean): EntityValue<Entity> | undefined {
const col = entity[prop] as Collection<AnyEntity>;
if (raw && col.isInitialized(true)) {
return col.map(item => helper(item).toPOJO()) as EntityValue<Entity>;
}
if (col.shouldPopulate(populated)) {
return col.toArray() as EntityValue<Entity>;
}
if (col.isInitialized()) {
const wrapped = helper(entity);
if (wrapped.__config.get('serialization').forceObject) {
return col.map(item => {
const wrapped = helper(item);
return Utils.primaryKeyToObject(wrapped.__meta, wrapped.getPrimaryKey(true)!) as EntityValue<Entity>;
}) as EntityValue<Entity>;
}
return col.map(i => helper(i).getPrimaryKey(true)) as EntityValue<Entity>;
}
return undefined;
}
}