@mikro-orm/core 7.0.0-dev.33 → 7.0.0-dev.331

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/EntityManager.d.ts +70 -75
  2. package/EntityManager.js +487 -402
  3. package/MikroORM.d.ts +45 -38
  4. package/MikroORM.js +123 -156
  5. package/README.md +7 -4
  6. package/cache/FileCacheAdapter.d.ts +2 -7
  7. package/cache/FileCacheAdapter.js +35 -30
  8. package/cache/GeneratedCacheAdapter.d.ts +1 -2
  9. package/cache/GeneratedCacheAdapter.js +6 -8
  10. package/cache/MemoryCacheAdapter.d.ts +1 -2
  11. package/cache/MemoryCacheAdapter.js +8 -8
  12. package/cache/index.d.ts +1 -2
  13. package/cache/index.js +0 -2
  14. package/connections/Connection.d.ts +12 -5
  15. package/connections/Connection.js +37 -15
  16. package/drivers/DatabaseDriver.d.ts +25 -18
  17. package/drivers/DatabaseDriver.js +144 -45
  18. package/drivers/IDatabaseDriver.d.ts +118 -23
  19. package/entity/BaseEntity.d.ts +63 -4
  20. package/entity/BaseEntity.js +0 -3
  21. package/entity/Collection.d.ts +95 -31
  22. package/entity/Collection.js +487 -139
  23. package/entity/EntityAssigner.js +37 -25
  24. package/entity/EntityFactory.d.ts +8 -9
  25. package/entity/EntityFactory.js +152 -100
  26. package/entity/EntityHelper.d.ts +2 -2
  27. package/entity/EntityHelper.js +69 -27
  28. package/entity/EntityLoader.d.ts +12 -13
  29. package/entity/EntityLoader.js +286 -125
  30. package/entity/EntityRepository.d.ts +28 -8
  31. package/entity/EntityRepository.js +8 -2
  32. package/entity/PolymorphicRef.d.ts +12 -0
  33. package/entity/PolymorphicRef.js +18 -0
  34. package/entity/Reference.d.ts +3 -8
  35. package/entity/Reference.js +62 -29
  36. package/entity/WrappedEntity.d.ts +7 -10
  37. package/entity/WrappedEntity.js +6 -7
  38. package/entity/defineEntity.d.ts +472 -313
  39. package/entity/defineEntity.js +134 -290
  40. package/entity/index.d.ts +2 -2
  41. package/entity/index.js +2 -2
  42. package/entity/utils.d.ts +6 -1
  43. package/entity/utils.js +46 -11
  44. package/entity/validators.d.ts +11 -0
  45. package/entity/validators.js +66 -0
  46. package/enums.d.ts +8 -6
  47. package/enums.js +13 -17
  48. package/errors.d.ts +26 -16
  49. package/errors.js +63 -31
  50. package/events/EventManager.d.ts +3 -5
  51. package/events/EventManager.js +37 -26
  52. package/events/index.d.ts +1 -1
  53. package/events/index.js +0 -1
  54. package/exceptions.js +9 -2
  55. package/hydration/Hydrator.js +1 -2
  56. package/hydration/ObjectHydrator.d.ts +5 -6
  57. package/hydration/ObjectHydrator.js +109 -50
  58. package/index.d.ts +2 -2
  59. package/index.js +1 -2
  60. package/logging/DefaultLogger.d.ts +1 -1
  61. package/logging/DefaultLogger.js +3 -4
  62. package/logging/SimpleLogger.d.ts +1 -1
  63. package/logging/colors.d.ts +1 -1
  64. package/logging/colors.js +4 -6
  65. package/logging/index.d.ts +2 -1
  66. package/logging/index.js +1 -1
  67. package/logging/inspect.d.ts +2 -0
  68. package/logging/inspect.js +11 -0
  69. package/metadata/EntitySchema.d.ts +47 -23
  70. package/metadata/EntitySchema.js +103 -34
  71. package/metadata/MetadataDiscovery.d.ts +65 -18
  72. package/metadata/MetadataDiscovery.js +940 -424
  73. package/metadata/MetadataProvider.d.ts +11 -2
  74. package/metadata/MetadataProvider.js +71 -2
  75. package/metadata/MetadataStorage.d.ts +11 -13
  76. package/metadata/MetadataStorage.js +79 -48
  77. package/metadata/MetadataValidator.d.ts +32 -9
  78. package/metadata/MetadataValidator.js +214 -44
  79. package/metadata/discover-entities.d.ts +5 -0
  80. package/metadata/discover-entities.js +40 -0
  81. package/metadata/index.d.ts +1 -1
  82. package/metadata/index.js +0 -1
  83. package/metadata/types.d.ts +577 -0
  84. package/metadata/types.js +1 -0
  85. package/naming-strategy/AbstractNamingStrategy.d.ts +16 -4
  86. package/naming-strategy/AbstractNamingStrategy.js +26 -5
  87. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  88. package/naming-strategy/EntityCaseNamingStrategy.js +7 -6
  89. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  90. package/naming-strategy/MongoNamingStrategy.js +6 -6
  91. package/naming-strategy/NamingStrategy.d.ts +28 -4
  92. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  93. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  94. package/naming-strategy/index.d.ts +1 -1
  95. package/naming-strategy/index.js +0 -1
  96. package/not-supported.d.ts +2 -0
  97. package/not-supported.js +8 -0
  98. package/package.json +47 -36
  99. package/platforms/ExceptionConverter.js +1 -1
  100. package/platforms/Platform.d.ts +33 -15
  101. package/platforms/Platform.js +125 -69
  102. package/serialization/EntitySerializer.d.ts +6 -3
  103. package/serialization/EntitySerializer.js +54 -30
  104. package/serialization/EntityTransformer.js +37 -22
  105. package/serialization/SerializationContext.d.ts +10 -14
  106. package/serialization/SerializationContext.js +24 -19
  107. package/types/ArrayType.d.ts +1 -1
  108. package/types/ArrayType.js +2 -3
  109. package/types/BigIntType.js +1 -1
  110. package/types/BlobType.d.ts +0 -1
  111. package/types/BlobType.js +0 -3
  112. package/types/BooleanType.d.ts +1 -0
  113. package/types/BooleanType.js +3 -0
  114. package/types/DecimalType.js +2 -2
  115. package/types/DoubleType.js +1 -1
  116. package/types/EnumArrayType.js +1 -2
  117. package/types/JsonType.d.ts +1 -1
  118. package/types/JsonType.js +7 -2
  119. package/types/TinyIntType.js +1 -1
  120. package/types/Type.d.ts +2 -4
  121. package/types/Type.js +3 -3
  122. package/types/Uint8ArrayType.d.ts +0 -1
  123. package/types/Uint8ArrayType.js +1 -4
  124. package/types/UuidType.d.ts +2 -0
  125. package/types/UuidType.js +14 -2
  126. package/types/index.d.ts +3 -2
  127. package/typings.d.ts +427 -170
  128. package/typings.js +100 -45
  129. package/unit-of-work/ChangeSet.d.ts +4 -6
  130. package/unit-of-work/ChangeSet.js +8 -9
  131. package/unit-of-work/ChangeSetComputer.d.ts +2 -12
  132. package/unit-of-work/ChangeSetComputer.js +61 -38
  133. package/unit-of-work/ChangeSetPersister.d.ts +10 -17
  134. package/unit-of-work/ChangeSetPersister.js +136 -73
  135. package/unit-of-work/CommitOrderCalculator.d.ts +13 -14
  136. package/unit-of-work/CommitOrderCalculator.js +22 -20
  137. package/unit-of-work/IdentityMap.d.ts +12 -3
  138. package/unit-of-work/IdentityMap.js +51 -13
  139. package/unit-of-work/UnitOfWork.d.ts +39 -23
  140. package/unit-of-work/UnitOfWork.js +441 -246
  141. package/utils/AbstractMigrator.d.ts +101 -0
  142. package/utils/AbstractMigrator.js +303 -0
  143. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  144. package/utils/AbstractSchemaGenerator.js +30 -18
  145. package/utils/AsyncContext.d.ts +6 -0
  146. package/utils/AsyncContext.js +42 -0
  147. package/utils/Configuration.d.ts +647 -185
  148. package/utils/Configuration.js +215 -252
  149. package/utils/ConfigurationLoader.d.ts +1 -52
  150. package/utils/ConfigurationLoader.js +1 -330
  151. package/utils/Cursor.d.ts +3 -6
  152. package/utils/Cursor.js +32 -17
  153. package/utils/DataloaderUtils.d.ts +10 -5
  154. package/utils/DataloaderUtils.js +42 -22
  155. package/utils/EntityComparator.d.ts +21 -21
  156. package/utils/EntityComparator.js +224 -118
  157. package/utils/QueryHelper.d.ts +34 -7
  158. package/utils/QueryHelper.js +183 -72
  159. package/utils/RawQueryFragment.d.ts +28 -34
  160. package/utils/RawQueryFragment.js +37 -72
  161. package/utils/RequestContext.js +2 -2
  162. package/utils/TransactionContext.js +2 -2
  163. package/utils/TransactionManager.js +11 -8
  164. package/utils/Utils.d.ts +16 -127
  165. package/utils/Utils.js +104 -402
  166. package/utils/clone.js +13 -23
  167. package/utils/env-vars.d.ts +7 -0
  168. package/utils/env-vars.js +98 -0
  169. package/utils/fs-utils.d.ts +20 -0
  170. package/utils/fs-utils.js +193 -0
  171. package/utils/index.d.ts +1 -3
  172. package/utils/index.js +1 -3
  173. package/utils/upsert-utils.d.ts +9 -4
  174. package/utils/upsert-utils.js +51 -5
  175. package/decorators/Check.d.ts +0 -3
  176. package/decorators/Check.js +0 -13
  177. package/decorators/CreateRequestContext.d.ts +0 -3
  178. package/decorators/CreateRequestContext.js +0 -32
  179. package/decorators/Embeddable.d.ts +0 -8
  180. package/decorators/Embeddable.js +0 -11
  181. package/decorators/Embedded.d.ts +0 -12
  182. package/decorators/Embedded.js +0 -18
  183. package/decorators/Entity.d.ts +0 -33
  184. package/decorators/Entity.js +0 -12
  185. package/decorators/Enum.d.ts +0 -9
  186. package/decorators/Enum.js +0 -16
  187. package/decorators/Filter.d.ts +0 -2
  188. package/decorators/Filter.js +0 -8
  189. package/decorators/Formula.d.ts +0 -4
  190. package/decorators/Formula.js +0 -15
  191. package/decorators/Indexed.d.ts +0 -19
  192. package/decorators/Indexed.js +0 -20
  193. package/decorators/ManyToMany.d.ts +0 -42
  194. package/decorators/ManyToMany.js +0 -14
  195. package/decorators/ManyToOne.d.ts +0 -34
  196. package/decorators/ManyToOne.js +0 -14
  197. package/decorators/OneToMany.d.ts +0 -28
  198. package/decorators/OneToMany.js +0 -17
  199. package/decorators/OneToOne.d.ts +0 -28
  200. package/decorators/OneToOne.js +0 -7
  201. package/decorators/PrimaryKey.d.ts +0 -8
  202. package/decorators/PrimaryKey.js +0 -20
  203. package/decorators/Property.d.ts +0 -250
  204. package/decorators/Property.js +0 -32
  205. package/decorators/Transactional.d.ts +0 -14
  206. package/decorators/Transactional.js +0 -28
  207. package/decorators/hooks.d.ts +0 -16
  208. package/decorators/hooks.js +0 -47
  209. package/decorators/index.d.ts +0 -17
  210. package/decorators/index.js +0 -17
  211. package/entity/ArrayCollection.d.ts +0 -118
  212. package/entity/ArrayCollection.js +0 -407
  213. package/entity/EntityValidator.d.ts +0 -19
  214. package/entity/EntityValidator.js +0 -150
  215. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  216. package/metadata/ReflectMetadataProvider.js +0 -44
  217. package/utils/resolveContextProvider.d.ts +0 -10
  218. package/utils/resolveContextProvider.js +0 -28
@@ -1,407 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import { Reference } from './Reference.js';
3
- import { helper, wrap } from './wrap.js';
4
- import { MetadataError, ValidationError } from '../errors.js';
5
- import { ReferenceKind } from '../enums.js';
6
- import { Utils } from '../utils/Utils.js';
7
- export class ArrayCollection {
8
- owner;
9
- items = new Set();
10
- initialized = true;
11
- dirty = false;
12
- partial = false; // mark partially loaded collections, propagation is disabled for those
13
- snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
14
- _count;
15
- _property;
16
- constructor(owner, items) {
17
- this.owner = owner;
18
- /* v8 ignore next 5 */
19
- if (items) {
20
- let i = 0;
21
- this.items = new Set(items);
22
- this.items.forEach(item => this[i++] = item);
23
- }
24
- }
25
- async loadCount() {
26
- return this.items.size;
27
- }
28
- getItems() {
29
- return [...this.items];
30
- }
31
- toArray() {
32
- if (this.items.size === 0) {
33
- return [];
34
- }
35
- const meta = this.property.targetMeta;
36
- const args = meta.toJsonParams.map(() => undefined);
37
- return this.map(item => wrap(item).toJSON(...args));
38
- }
39
- toJSON() {
40
- return this.toArray();
41
- }
42
- getIdentifiers(field) {
43
- const items = this.getItems();
44
- const targetMeta = this.property.targetMeta;
45
- if (items.length === 0) {
46
- return [];
47
- }
48
- field ??= targetMeta.compositePK ? targetMeta.primaryKeys : targetMeta.serializedPrimaryKey;
49
- const cb = (i, f) => {
50
- if (Utils.isEntity(i[f], true)) {
51
- return wrap(i[f], true).getPrimaryKey();
52
- }
53
- return i[f];
54
- };
55
- return items.map(i => {
56
- if (Array.isArray(field)) {
57
- return field.map(f => cb(i, f));
58
- }
59
- return cb(i, field);
60
- });
61
- }
62
- add(entity, ...entities) {
63
- entities = Utils.asArray(entity).concat(entities);
64
- for (const item of entities) {
65
- const entity = Reference.unwrapReference(item);
66
- if (!this.contains(entity, false)) {
67
- this.incrementCount(1);
68
- this[this.items.size] = entity;
69
- this.items.add(entity);
70
- this.propagate(entity, 'add');
71
- }
72
- }
73
- }
74
- /**
75
- * @internal
76
- */
77
- addWithoutPropagation(entity) {
78
- if (!this.contains(entity, false)) {
79
- this.incrementCount(1);
80
- this[this.items.size] = entity;
81
- this.items.add(entity);
82
- this.dirty = true;
83
- }
84
- }
85
- set(items) {
86
- if (!this.initialized) {
87
- this.initialized = true;
88
- this.snapshot = undefined;
89
- }
90
- if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
91
- return;
92
- }
93
- this.remove(this.items);
94
- this.add(items);
95
- }
96
- compare(items) {
97
- if (items.length !== this.items.size) {
98
- return false;
99
- }
100
- let idx = 0;
101
- for (const item of this.items) {
102
- if (item !== items[idx++]) {
103
- return false;
104
- }
105
- }
106
- return true;
107
- }
108
- /**
109
- * @internal
110
- */
111
- hydrate(items, forcePropagate, partial) {
112
- for (let i = 0; i < this.items.size; i++) {
113
- delete this[i];
114
- }
115
- this.initialized = true;
116
- this.partial = !!partial;
117
- this.items.clear();
118
- this._count = 0;
119
- this.add(items);
120
- this.takeSnapshot(forcePropagate);
121
- }
122
- /**
123
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
124
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
125
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
126
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
127
- */
128
- remove(entity, ...entities) {
129
- entities = Utils.asArray(entity).concat(entities);
130
- let modified = false;
131
- for (const item of entities) {
132
- if (!item) {
133
- continue;
134
- }
135
- const entity = Reference.unwrapReference(item);
136
- if (this.items.delete(entity)) {
137
- this.incrementCount(-1);
138
- delete this[this.items.size]; // remove last item
139
- this.propagate(entity, 'remove');
140
- modified = true;
141
- }
142
- }
143
- if (modified) {
144
- Object.assign(this, [...this.items]); // reassign array access
145
- }
146
- }
147
- /**
148
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
149
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
150
- * is not the same as `em.remove()`. If we want to delete the entity by removing it from collection, we need to enable `orphanRemoval: true`,
151
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
152
- */
153
- removeAll() {
154
- if (!this.initialized) {
155
- this.initialized = true;
156
- this.snapshot = undefined;
157
- }
158
- this.remove(this.items);
159
- }
160
- /**
161
- * @internal
162
- */
163
- removeWithoutPropagation(entity) {
164
- if (!this.items.delete(entity)) {
165
- return;
166
- }
167
- this.incrementCount(-1);
168
- delete this[this.items.size];
169
- Object.assign(this, [...this.items]);
170
- this.dirty = true;
171
- }
172
- contains(item, check) {
173
- const entity = Reference.unwrapReference(item);
174
- return this.items.has(entity);
175
- }
176
- /**
177
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
178
- * If end is null it returns all elements from start to the end of the collection.
179
- */
180
- slice(start = 0, end) {
181
- let index = 0;
182
- end ??= this.items.size;
183
- const items = [];
184
- for (const item of this.items) {
185
- if (index === end) {
186
- break;
187
- }
188
- if (index >= start && index < end) {
189
- items.push(item);
190
- }
191
- index++;
192
- }
193
- return items;
194
- }
195
- /**
196
- * Tests for the existence of an element that satisfies the given predicate.
197
- */
198
- exists(cb) {
199
- for (const item of this.items) {
200
- if (cb(item)) {
201
- return true;
202
- }
203
- }
204
- return false;
205
- }
206
- /**
207
- * Returns the first element of this collection that satisfies the predicate.
208
- */
209
- find(cb) {
210
- let index = 0;
211
- for (const item of this.items) {
212
- if (cb(item, index++)) {
213
- return item;
214
- }
215
- }
216
- return undefined;
217
- }
218
- /**
219
- * Extracts a subset of the collection items.
220
- */
221
- filter(cb) {
222
- const items = [];
223
- let index = 0;
224
- for (const item of this.items) {
225
- if (cb(item, index++)) {
226
- items.push(item);
227
- }
228
- }
229
- return items;
230
- }
231
- /**
232
- * Maps the collection items based on your provided mapper function.
233
- */
234
- map(mapper) {
235
- const items = [];
236
- let index = 0;
237
- for (const item of this.items) {
238
- items.push(mapper(item, index++));
239
- }
240
- return items;
241
- }
242
- /**
243
- * Maps the collection items based on your provided mapper function to a single object.
244
- */
245
- reduce(cb, initial = {}) {
246
- let index = 0;
247
- for (const item of this.items) {
248
- initial = cb(initial, item, index++);
249
- }
250
- return initial;
251
- }
252
- /**
253
- * Maps the collection items to a dictionary, indexed by the key you specify.
254
- * If there are more items with the same key, only the first one will be present.
255
- */
256
- indexBy(key, valueKey) {
257
- return this.reduce((obj, item) => {
258
- obj[item[key]] ??= valueKey ? item[valueKey] : item;
259
- return obj;
260
- }, {});
261
- }
262
- count() {
263
- return this.items.size;
264
- }
265
- isInitialized(fully = false) {
266
- if (!this.initialized || !fully) {
267
- return this.initialized;
268
- }
269
- for (const item of this.items) {
270
- if (!helper(item).__initialized) {
271
- return false;
272
- }
273
- }
274
- return true;
275
- }
276
- isDirty() {
277
- return this.dirty;
278
- }
279
- isPartial() {
280
- return this.partial;
281
- }
282
- isEmpty() {
283
- return this.count() === 0;
284
- }
285
- setDirty(dirty = true) {
286
- this.dirty = dirty;
287
- }
288
- get length() {
289
- return this.count();
290
- }
291
- *[Symbol.iterator]() {
292
- for (const item of this.getItems()) {
293
- yield item;
294
- }
295
- }
296
- /**
297
- * @internal
298
- */
299
- takeSnapshot(forcePropagate) {
300
- this.snapshot = [...this.items];
301
- this.setDirty(false);
302
- if (this.property.owner || forcePropagate) {
303
- this.items.forEach(item => {
304
- this.propagate(item, 'takeSnapshot');
305
- });
306
- }
307
- }
308
- /**
309
- * @internal
310
- */
311
- getSnapshot() {
312
- return this.snapshot;
313
- }
314
- /**
315
- * @internal
316
- */
317
- get property() {
318
- if (!this._property) {
319
- const meta = wrap(this.owner, true).__meta;
320
- /* v8 ignore next 3 */
321
- if (!meta) {
322
- throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
323
- }
324
- this._property = meta.relations.find(prop => this.owner[prop.name] === this);
325
- }
326
- return this._property;
327
- }
328
- /**
329
- * @internal
330
- */
331
- set property(prop) {
332
- this._property = prop;
333
- }
334
- propagate(item, method) {
335
- if (this.property.owner && this.property.inversedBy) {
336
- this.propagateToInverseSide(item, method);
337
- }
338
- else if (!this.property.owner && this.property.mappedBy) {
339
- this.propagateToOwningSide(item, method);
340
- }
341
- }
342
- propagateToInverseSide(item, method) {
343
- const collection = item[this.property.inversedBy];
344
- if (this.shouldPropagateToCollection(collection, method)) {
345
- method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
346
- collection[method](this.owner);
347
- }
348
- }
349
- propagateToOwningSide(item, method) {
350
- const mappedBy = this.property.mappedBy;
351
- const collection = item[mappedBy];
352
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
353
- if (this.shouldPropagateToCollection(collection, method)) {
354
- collection[method](this.owner);
355
- }
356
- }
357
- else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
358
- const prop2 = this.property.targetMeta.properties[mappedBy];
359
- const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
360
- const value = method === 'add' ? owner : null;
361
- if (this.property.orphanRemoval && method === 'remove') {
362
- // cache the PK before we propagate, as its value might be needed when flushing
363
- helper(item).__pk = helper(item).getPrimaryKey();
364
- }
365
- if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
366
- if (!this.property.orphanRemoval) {
367
- throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
368
- }
369
- return;
370
- }
371
- // skip if already propagated
372
- if (Reference.unwrapReference(item[mappedBy]) !== value) {
373
- item[mappedBy] = value;
374
- }
375
- }
376
- }
377
- shouldPropagateToCollection(collection, method) {
378
- if (!collection) {
379
- return false;
380
- }
381
- switch (method) {
382
- case 'add':
383
- return !collection.contains(this.owner, false);
384
- case 'remove':
385
- return collection.isInitialized() && collection.contains(this.owner, false);
386
- case 'takeSnapshot':
387
- return collection.isDirty();
388
- }
389
- }
390
- incrementCount(value) {
391
- if (typeof this._count === 'number' && this.initialized) {
392
- this._count += value;
393
- }
394
- }
395
- /** @ignore */
396
- [inspect.custom](depth = 2) {
397
- const object = { ...this };
398
- const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly', 'partial'];
399
- hidden.forEach(k => delete object[k]);
400
- const ret = inspect(object, { depth });
401
- const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
402
- return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
403
- }
404
- }
405
- Object.defineProperties(ArrayCollection.prototype, {
406
- __collection: { value: true, enumerable: false, writable: false },
407
- });
@@ -1,19 +0,0 @@
1
- import type { EntityData, EntityMetadata, EntityProperty, FilterQuery } from '../typings.js';
2
- export declare class EntityValidator {
3
- private strict;
4
- KNOWN_TYPES: Set<string>;
5
- constructor(strict: boolean);
6
- validate<T extends object>(entity: T, payload: any, meta: EntityMetadata<T>): void;
7
- validateRequired<T extends object>(entity: T): void;
8
- validateProperty<T extends object>(prop: EntityProperty, givenValue: any, entity: T): any;
9
- validateParams(params: any, type?: string, field?: string): void;
10
- validatePrimaryKey<T>(entity: EntityData<T>, meta: EntityMetadata<T>): void;
11
- validateEmptyWhere<T>(where: FilterQuery<T>): void;
12
- private getValue;
13
- private setValue;
14
- private validateCollection;
15
- private fixTypes;
16
- private fixDateType;
17
- private fixNumberType;
18
- private fixBooleanType;
19
- }
@@ -1,150 +0,0 @@
1
- import { ReferenceKind } from '../enums.js';
2
- import { Utils } from '../utils/Utils.js';
3
- import { ValidationError } from '../errors.js';
4
- import { helper } from './wrap.js';
5
- import { RawQueryFragment } from '../utils/RawQueryFragment.js';
6
- export class EntityValidator {
7
- strict;
8
- KNOWN_TYPES = new Set(['string', 'number', 'boolean', 'bigint', 'Uint8Array', 'Date', 'Buffer', 'RegExp']);
9
- constructor(strict) {
10
- this.strict = strict;
11
- }
12
- validate(entity, payload, meta) {
13
- meta.props.forEach(prop => {
14
- if (prop.inherited || (prop.persist === false && prop.userDefined !== false)) {
15
- return;
16
- }
17
- if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind)) {
18
- this.validateCollection(entity, prop);
19
- }
20
- const SCALAR_TYPES = ['string', 'number', 'boolean', 'Date'];
21
- if (prop.kind !== ReferenceKind.SCALAR || !SCALAR_TYPES.includes(prop.type)) {
22
- return;
23
- }
24
- const newValue = this.validateProperty(prop, this.getValue(payload, prop), entity);
25
- if (this.getValue(payload, prop) === newValue) {
26
- return;
27
- }
28
- this.setValue(payload, prop, newValue);
29
- if (entity[prop.name]) {
30
- entity[prop.name] = payload[prop.name];
31
- }
32
- });
33
- }
34
- validateRequired(entity) {
35
- const wrapped = helper(entity);
36
- for (const prop of wrapped.__meta.props) {
37
- if (!prop.nullable &&
38
- !prop.autoincrement &&
39
- !prop.default &&
40
- !prop.defaultRaw &&
41
- !prop.onCreate &&
42
- !prop.generated &&
43
- !prop.embedded &&
44
- ![ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) &&
45
- prop.name !== wrapped.__meta.root.discriminatorColumn &&
46
- prop.type.toLowerCase() !== 'objectid' &&
47
- prop.persist !== false &&
48
- entity[prop.name] == null) {
49
- throw ValidationError.propertyRequired(entity, prop);
50
- }
51
- }
52
- }
53
- validateProperty(prop, givenValue, entity) {
54
- if (givenValue == null || givenValue instanceof RawQueryFragment) {
55
- return givenValue;
56
- }
57
- const expectedType = prop.runtimeType;
58
- const propName = prop.embedded ? prop.name.replace(/~/g, '.') : prop.name;
59
- let givenType = Utils.getObjectType(givenValue);
60
- let ret = givenValue;
61
- if (!this.strict) {
62
- ret = this.fixTypes(expectedType, givenType, givenValue);
63
- givenType = Utils.getObjectType(ret);
64
- }
65
- if (prop.enum && prop.items) {
66
- /* v8 ignore next 3 */
67
- if (!prop.items.some(it => it === givenValue)) {
68
- throw ValidationError.fromWrongPropertyType(entity, propName, expectedType, givenType, givenValue);
69
- }
70
- }
71
- else {
72
- if (givenType !== expectedType && this.KNOWN_TYPES.has(expectedType)) {
73
- throw ValidationError.fromWrongPropertyType(entity, propName, expectedType, givenType, givenValue);
74
- }
75
- }
76
- return ret;
77
- }
78
- validateParams(params, type = 'search condition', field) {
79
- if (Utils.isPrimaryKey(params) || Utils.isEntity(params)) {
80
- return;
81
- }
82
- if (Array.isArray(params)) {
83
- return params.forEach(item => this.validateParams(item, type, field));
84
- }
85
- if (Utils.isPlainObject(params)) {
86
- Object.keys(params).forEach(k => {
87
- this.validateParams(params[k], type, k);
88
- });
89
- }
90
- }
91
- validatePrimaryKey(entity, meta) {
92
- const pkExists = meta.primaryKeys.every(pk => entity[pk] != null) || entity[meta.serializedPrimaryKey] != null;
93
- if (!entity || !pkExists) {
94
- throw ValidationError.fromMergeWithoutPK(meta);
95
- }
96
- }
97
- validateEmptyWhere(where) {
98
- if (Utils.isEmpty(where)) {
99
- throw new Error(`You cannot call 'EntityManager.findOne()' with empty 'where' parameter`);
100
- }
101
- }
102
- getValue(o, prop) {
103
- if (prop.embedded && prop.embedded[0] in o) {
104
- return o[prop.embedded[0]]?.[prop.embedded[1]];
105
- }
106
- return o[prop.name];
107
- }
108
- setValue(o, prop, v) {
109
- /* v8 ignore next 3 */
110
- if (prop.embedded && prop.embedded[0] in o) {
111
- return o[prop.embedded[0]][prop.embedded[1]] = v;
112
- }
113
- o[prop.name] = v;
114
- }
115
- validateCollection(entity, prop) {
116
- if (prop.hydrate !== false && helper(entity).__initialized && !entity[prop.name]) {
117
- throw ValidationError.fromCollectionNotInitialized(entity, prop);
118
- }
119
- }
120
- fixTypes(expectedType, givenType, givenValue) {
121
- if (expectedType === 'Date' && ['string', 'number'].includes(givenType)) {
122
- givenValue = this.fixDateType(givenValue);
123
- }
124
- if (expectedType === 'number' && givenType === 'string') {
125
- givenValue = this.fixNumberType(givenValue);
126
- }
127
- if (expectedType === 'boolean' && givenType === 'number') {
128
- givenValue = this.fixBooleanType(givenValue);
129
- }
130
- return givenValue;
131
- }
132
- fixDateType(givenValue) {
133
- let date;
134
- if (Utils.isString(givenValue) && givenValue.match(/^-?\d+(\.\d+)?$/)) {
135
- date = new Date(+givenValue);
136
- }
137
- else {
138
- date = new Date(givenValue);
139
- }
140
- return date.toString() !== 'Invalid Date' ? date : givenValue;
141
- }
142
- fixNumberType(givenValue) {
143
- const num = +givenValue;
144
- return '' + num === givenValue ? num : givenValue;
145
- }
146
- fixBooleanType(givenValue) {
147
- const bool = !!givenValue;
148
- return +bool === givenValue ? bool : givenValue;
149
- }
150
- }
@@ -1,8 +0,0 @@
1
- import 'reflect-metadata';
2
- import type { EntityMetadata, EntityProperty } from '../typings.js';
3
- import { MetadataProvider } from './MetadataProvider.js';
4
- export declare class ReflectMetadataProvider extends MetadataProvider {
5
- loadEntityMetadata(meta: EntityMetadata, name: string): void;
6
- protected initProperties(meta: EntityMetadata): void;
7
- protected initPropertyType(meta: EntityMetadata, prop: EntityProperty): void;
8
- }
@@ -1,44 +0,0 @@
1
- import 'reflect-metadata';
2
- import { MetadataProvider } from './MetadataProvider.js';
3
- import { ReferenceKind } from '../enums.js';
4
- import { Utils } from '../utils/Utils.js';
5
- export class ReflectMetadataProvider extends MetadataProvider {
6
- loadEntityMetadata(meta, name) {
7
- this.initProperties(meta);
8
- }
9
- initProperties(meta) {
10
- // load types and column names
11
- for (const prop of meta.props) {
12
- if (typeof prop.entity === 'string') {
13
- prop.type = prop.entity;
14
- }
15
- else if (prop.entity) {
16
- const tmp = prop.entity();
17
- prop.type = Array.isArray(tmp) ? tmp.map(t => Utils.className(t)).sort().join(' | ') : Utils.className(tmp);
18
- }
19
- else {
20
- this.initPropertyType(meta, prop);
21
- }
22
- }
23
- }
24
- initPropertyType(meta, prop) {
25
- const type = Reflect.getMetadata('design:type', meta.prototype, prop.name);
26
- if (!prop.type && (!type || (type === Object && prop.kind !== ReferenceKind.SCALAR)) && !(prop.enum && (prop.items?.length ?? 0) > 0)) {
27
- throw new Error(`Please provide either 'type' or 'entity' attribute in ${meta.className}.${prop.name}. If you are using decorators, ensure you have 'emitDecoratorMetadata' enabled in your tsconfig.json.`);
28
- }
29
- // Force mapping to UnknownType which is a string when we see just `Object`, as that often means failed inference.
30
- // This is to prevent defaulting to JSON column type, which can often be hard to revert and cause hard to understand issues with PKs.
31
- // If there are explicitly provided `columnTypes`, we use those instead for the inference, this way
32
- // we can have things like `columnType: 'timestamp'` be respected as `type: 'Date'`.
33
- if (prop.kind === ReferenceKind.SCALAR && type === Object && !prop.columnTypes) {
34
- prop.type ??= 'any';
35
- return;
36
- }
37
- let typeName = type?.name;
38
- if (typeName && ['string', 'number', 'boolean', 'array', 'object'].includes(typeName.toLowerCase())) {
39
- typeName = typeName.toLowerCase();
40
- }
41
- prop.type ??= typeName;
42
- prop.runtimeType ??= typeName;
43
- }
44
- }
@@ -1,10 +0,0 @@
1
- import { EntityManager } from '../EntityManager.js';
2
- import { MikroORM } from '../MikroORM.js';
3
- import type { ContextProvider, MaybePromise } from '../typings.js';
4
- /**
5
- * Find `EntityManager` in provided context, or else in instance's `orm` or `em` properties.
6
- */
7
- export declare function resolveContextProvider<T>(caller: T & {
8
- orm?: MaybePromise<MikroORM>;
9
- em?: MaybePromise<EntityManager>;
10
- }, provider?: ContextProvider<T>): Promise<EntityManager | undefined>;
@@ -1,28 +0,0 @@
1
- import { EntityRepository } from '../entity/EntityRepository.js';
2
- import { EntityManager } from '../EntityManager.js';
3
- import { MikroORM } from '../MikroORM.js';
4
- function getEntityManager(caller, context) {
5
- if (context instanceof EntityManager) {
6
- return context;
7
- }
8
- if (context instanceof EntityRepository) {
9
- return context.getEntityManager();
10
- }
11
- if (context instanceof MikroORM) {
12
- return context.em;
13
- }
14
- if (caller.em instanceof EntityManager) {
15
- return caller.em;
16
- }
17
- if (caller.orm instanceof MikroORM) {
18
- return caller.orm.em;
19
- }
20
- return undefined;
21
- }
22
- /**
23
- * Find `EntityManager` in provided context, or else in instance's `orm` or `em` properties.
24
- */
25
- export async function resolveContextProvider(caller, provider) {
26
- const context = typeof provider === 'function' ? await provider(caller) : await provider;
27
- return getEntityManager({ orm: await caller.orm, em: await caller.em }, context);
28
- }