@mikro-orm/core 7.0.0-dev.8 → 7.0.0-dev.81

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 (181) hide show
  1. package/EntityManager.d.ts +85 -48
  2. package/EntityManager.js +300 -225
  3. package/MikroORM.d.ts +40 -31
  4. package/MikroORM.js +98 -137
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +6 -5
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +11 -7
  13. package/connections/Connection.js +16 -14
  14. package/drivers/DatabaseDriver.d.ts +11 -5
  15. package/drivers/DatabaseDriver.js +23 -11
  16. package/drivers/IDatabaseDriver.d.ts +27 -5
  17. package/entity/BaseEntity.d.ts +0 -1
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +98 -30
  20. package/entity/Collection.js +432 -93
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +15 -7
  23. package/entity/EntityFactory.d.ts +7 -0
  24. package/entity/EntityFactory.js +64 -41
  25. package/entity/EntityHelper.js +26 -9
  26. package/entity/EntityLoader.d.ts +5 -4
  27. package/entity/EntityLoader.js +73 -40
  28. package/entity/EntityRepository.d.ts +1 -1
  29. package/entity/Reference.d.ts +9 -7
  30. package/entity/Reference.js +33 -6
  31. package/entity/WrappedEntity.d.ts +2 -4
  32. package/entity/WrappedEntity.js +1 -5
  33. package/entity/defineEntity.d.ts +549 -0
  34. package/entity/defineEntity.js +529 -0
  35. package/entity/index.d.ts +3 -2
  36. package/entity/index.js +3 -2
  37. package/entity/utils.d.ts +7 -0
  38. package/entity/utils.js +16 -4
  39. package/entity/validators.d.ts +11 -0
  40. package/entity/validators.js +65 -0
  41. package/enums.d.ts +21 -6
  42. package/enums.js +14 -1
  43. package/errors.d.ts +6 -2
  44. package/errors.js +14 -9
  45. package/events/EventSubscriber.d.ts +3 -1
  46. package/hydration/Hydrator.js +1 -2
  47. package/hydration/ObjectHydrator.d.ts +4 -4
  48. package/hydration/ObjectHydrator.js +36 -25
  49. package/index.d.ts +2 -2
  50. package/index.js +1 -2
  51. package/logging/DefaultLogger.d.ts +1 -1
  52. package/logging/SimpleLogger.d.ts +1 -1
  53. package/metadata/EntitySchema.d.ts +9 -13
  54. package/metadata/EntitySchema.js +44 -26
  55. package/metadata/MetadataDiscovery.d.ts +6 -9
  56. package/metadata/MetadataDiscovery.js +167 -206
  57. package/metadata/MetadataProvider.d.ts +11 -2
  58. package/metadata/MetadataProvider.js +44 -2
  59. package/metadata/MetadataStorage.d.ts +1 -6
  60. package/metadata/MetadataStorage.js +6 -18
  61. package/metadata/MetadataValidator.d.ts +0 -7
  62. package/metadata/MetadataValidator.js +4 -13
  63. package/metadata/discover-entities.d.ts +5 -0
  64. package/metadata/discover-entities.js +40 -0
  65. package/metadata/index.d.ts +1 -1
  66. package/metadata/index.js +1 -1
  67. package/metadata/types.d.ts +480 -0
  68. package/metadata/types.js +1 -0
  69. package/naming-strategy/AbstractNamingStrategy.d.ts +5 -1
  70. package/naming-strategy/AbstractNamingStrategy.js +8 -2
  71. package/naming-strategy/NamingStrategy.d.ts +11 -1
  72. package/not-supported.d.ts +2 -0
  73. package/not-supported.js +4 -0
  74. package/package.json +18 -10
  75. package/platforms/ExceptionConverter.js +1 -1
  76. package/platforms/Platform.d.ts +6 -10
  77. package/platforms/Platform.js +14 -39
  78. package/serialization/EntitySerializer.d.ts +2 -0
  79. package/serialization/EntitySerializer.js +32 -14
  80. package/serialization/EntityTransformer.js +22 -12
  81. package/serialization/SerializationContext.js +16 -13
  82. package/types/ArrayType.d.ts +1 -1
  83. package/types/ArrayType.js +2 -3
  84. package/types/BigIntType.d.ts +8 -6
  85. package/types/BigIntType.js +1 -1
  86. package/types/BlobType.d.ts +0 -1
  87. package/types/BlobType.js +0 -3
  88. package/types/BooleanType.d.ts +2 -1
  89. package/types/BooleanType.js +3 -0
  90. package/types/DecimalType.d.ts +6 -4
  91. package/types/DecimalType.js +3 -3
  92. package/types/DoubleType.js +2 -2
  93. package/types/JsonType.d.ts +1 -1
  94. package/types/JsonType.js +7 -2
  95. package/types/TinyIntType.js +1 -1
  96. package/types/Type.d.ts +2 -1
  97. package/types/Type.js +1 -1
  98. package/types/Uint8ArrayType.d.ts +0 -1
  99. package/types/Uint8ArrayType.js +1 -4
  100. package/types/index.d.ts +1 -1
  101. package/typings.d.ts +113 -77
  102. package/typings.js +41 -35
  103. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  104. package/unit-of-work/ChangeSetComputer.js +11 -9
  105. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  106. package/unit-of-work/ChangeSetPersister.js +58 -20
  107. package/unit-of-work/UnitOfWork.d.ts +8 -1
  108. package/unit-of-work/UnitOfWork.js +115 -57
  109. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  110. package/utils/AbstractSchemaGenerator.js +11 -9
  111. package/utils/Configuration.d.ts +757 -206
  112. package/utils/Configuration.js +139 -187
  113. package/utils/ConfigurationLoader.d.ts +1 -54
  114. package/utils/ConfigurationLoader.js +1 -352
  115. package/utils/Cursor.d.ts +3 -3
  116. package/utils/Cursor.js +4 -1
  117. package/utils/DataloaderUtils.d.ts +15 -5
  118. package/utils/DataloaderUtils.js +54 -8
  119. package/utils/EntityComparator.d.ts +8 -4
  120. package/utils/EntityComparator.js +111 -64
  121. package/utils/QueryHelper.d.ts +9 -1
  122. package/utils/QueryHelper.js +70 -9
  123. package/utils/RawQueryFragment.d.ts +36 -4
  124. package/utils/RawQueryFragment.js +35 -14
  125. package/utils/TransactionManager.d.ts +65 -0
  126. package/utils/TransactionManager.js +223 -0
  127. package/utils/Utils.d.ts +8 -97
  128. package/utils/Utils.js +88 -303
  129. package/utils/clone.js +2 -3
  130. package/utils/env-vars.d.ts +3 -0
  131. package/utils/env-vars.js +87 -0
  132. package/utils/fs-utils.d.ts +12 -0
  133. package/utils/fs-utils.js +96 -0
  134. package/utils/index.d.ts +2 -1
  135. package/utils/index.js +2 -1
  136. package/utils/upsert-utils.d.ts +7 -2
  137. package/utils/upsert-utils.js +55 -4
  138. package/decorators/Check.d.ts +0 -3
  139. package/decorators/Check.js +0 -13
  140. package/decorators/CreateRequestContext.d.ts +0 -3
  141. package/decorators/CreateRequestContext.js +0 -32
  142. package/decorators/Embeddable.d.ts +0 -8
  143. package/decorators/Embeddable.js +0 -11
  144. package/decorators/Embedded.d.ts +0 -18
  145. package/decorators/Embedded.js +0 -18
  146. package/decorators/Entity.d.ts +0 -18
  147. package/decorators/Entity.js +0 -12
  148. package/decorators/Enum.d.ts +0 -9
  149. package/decorators/Enum.js +0 -16
  150. package/decorators/Filter.d.ts +0 -2
  151. package/decorators/Filter.js +0 -8
  152. package/decorators/Formula.d.ts +0 -4
  153. package/decorators/Formula.js +0 -15
  154. package/decorators/Indexed.d.ts +0 -19
  155. package/decorators/Indexed.js +0 -20
  156. package/decorators/ManyToMany.d.ts +0 -40
  157. package/decorators/ManyToMany.js +0 -14
  158. package/decorators/ManyToOne.d.ts +0 -30
  159. package/decorators/ManyToOne.js +0 -14
  160. package/decorators/OneToMany.d.ts +0 -28
  161. package/decorators/OneToMany.js +0 -17
  162. package/decorators/OneToOne.d.ts +0 -24
  163. package/decorators/OneToOne.js +0 -7
  164. package/decorators/PrimaryKey.d.ts +0 -8
  165. package/decorators/PrimaryKey.js +0 -20
  166. package/decorators/Property.d.ts +0 -250
  167. package/decorators/Property.js +0 -32
  168. package/decorators/Transactional.d.ts +0 -13
  169. package/decorators/Transactional.js +0 -28
  170. package/decorators/hooks.d.ts +0 -16
  171. package/decorators/hooks.js +0 -47
  172. package/decorators/index.d.ts +0 -17
  173. package/decorators/index.js +0 -17
  174. package/entity/ArrayCollection.d.ts +0 -116
  175. package/entity/ArrayCollection.js +0 -402
  176. package/entity/EntityValidator.d.ts +0 -19
  177. package/entity/EntityValidator.js +0 -150
  178. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  179. package/metadata/ReflectMetadataProvider.js +0 -44
  180. package/utils/resolveContextProvider.d.ts +0 -10
  181. package/utils/resolveContextProvider.js +0 -28
@@ -1,116 +0,0 @@
1
- import { inspect } from 'node:util';
2
- import type { EntityDTO, EntityProperty, IPrimaryKey, Primary } from '../typings.js';
3
- import { Reference } from './Reference.js';
4
- export declare class ArrayCollection<T extends object, O extends object> {
5
- readonly owner: O;
6
- protected readonly items: Set<T>;
7
- protected initialized: boolean;
8
- protected dirty: boolean;
9
- protected snapshot: T[] | undefined;
10
- protected _count?: number;
11
- private _property?;
12
- constructor(owner: O, items?: T[]);
13
- loadCount(): Promise<number>;
14
- getItems(): T[];
15
- toArray<TT extends T>(): EntityDTO<TT>[];
16
- toJSON(): EntityDTO<T>[];
17
- getIdentifiers<U extends IPrimaryKey = Primary<T> & IPrimaryKey>(field?: string | string[]): U[];
18
- add(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): void;
19
- /**
20
- * @internal
21
- */
22
- addWithoutPropagation(entity: T): void;
23
- set(items: Iterable<T | Reference<T>>): void;
24
- private compare;
25
- /**
26
- * @internal
27
- */
28
- hydrate(items: T[], forcePropagate?: boolean): void;
29
- /**
30
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
31
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
32
- * 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`,
33
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
34
- */
35
- remove(entity: T | Reference<T> | Iterable<T | Reference<T>>, ...entities: (T | Reference<T>)[]): void;
36
- /**
37
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
38
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
39
- * 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`,
40
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
41
- */
42
- removeAll(): void;
43
- /**
44
- * @internal
45
- */
46
- removeWithoutPropagation(entity: T): void;
47
- contains(item: T | Reference<T>, check?: boolean): boolean;
48
- /**
49
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
50
- * If end is null it returns all elements from start to the end of the collection.
51
- */
52
- slice(start?: number, end?: number): T[];
53
- /**
54
- * Tests for the existence of an element that satisfies the given predicate.
55
- */
56
- exists(cb: (item: T) => boolean): boolean;
57
- /**
58
- * Returns the first element of this collection that satisfies the predicate.
59
- */
60
- find(cb: (item: T, index: number) => boolean): T | undefined;
61
- /**
62
- * Extracts a subset of the collection items.
63
- */
64
- filter(cb: (item: T, index: number) => boolean): T[];
65
- /**
66
- * Maps the collection items based on your provided mapper function.
67
- */
68
- map<R>(mapper: (item: T, index: number) => R): R[];
69
- /**
70
- * Maps the collection items based on your provided mapper function to a single object.
71
- */
72
- reduce<R>(cb: (obj: R, item: T, index: number) => R, initial?: R): R;
73
- /**
74
- * Maps the collection items to a dictionary, indexed by the key you specify.
75
- * If there are more items with the same key, only the first one will be present.
76
- */
77
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1): Record<T[K1] & PropertyKey, T>;
78
- /**
79
- * Maps the collection items to a dictionary, indexed by the key you specify.
80
- * If there are more items with the same key, only the first one will be present.
81
- */
82
- indexBy<K1 extends keyof T, K2 extends keyof T = never>(key: K1, valueKey: K2): Record<T[K1] & PropertyKey, T[K2]>;
83
- count(): number;
84
- isInitialized(fully?: boolean): boolean;
85
- isDirty(): boolean;
86
- isEmpty(): boolean;
87
- setDirty(dirty?: boolean): void;
88
- get length(): number;
89
- [Symbol.iterator](): IterableIterator<T>;
90
- /**
91
- * @internal
92
- */
93
- takeSnapshot(forcePropagate?: boolean): void;
94
- /**
95
- * @internal
96
- */
97
- getSnapshot(): T[] | undefined;
98
- /**
99
- * @internal
100
- */
101
- get property(): EntityProperty;
102
- /**
103
- * @internal
104
- */
105
- set property(prop: EntityProperty);
106
- protected propagate(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
107
- protected propagateToInverseSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
108
- protected propagateToOwningSide(item: T, method: 'add' | 'remove' | 'takeSnapshot'): void;
109
- protected shouldPropagateToCollection(collection: ArrayCollection<O, T>, method: 'add' | 'remove' | 'takeSnapshot'): boolean;
110
- protected incrementCount(value: number): void;
111
- /** @ignore */
112
- [inspect.custom](depth?: number): string;
113
- }
114
- export interface ArrayCollection<T, O> {
115
- [k: number]: T;
116
- }
@@ -1,402 +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
- snapshot = []; // used to create a diff of the collection at commit time, undefined marks overridden values so we need to wipe when flushing
13
- _count;
14
- _property;
15
- constructor(owner, items) {
16
- this.owner = owner;
17
- /* v8 ignore next 5 */
18
- if (items) {
19
- let i = 0;
20
- this.items = new Set(items);
21
- this.items.forEach(item => this[i++] = item);
22
- }
23
- }
24
- async loadCount() {
25
- return this.items.size;
26
- }
27
- getItems() {
28
- return [...this.items];
29
- }
30
- toArray() {
31
- if (this.items.size === 0) {
32
- return [];
33
- }
34
- const meta = this.property.targetMeta;
35
- const args = meta.toJsonParams.map(() => undefined);
36
- return this.map(item => wrap(item).toJSON(...args));
37
- }
38
- toJSON() {
39
- return this.toArray();
40
- }
41
- getIdentifiers(field) {
42
- const items = this.getItems();
43
- const targetMeta = this.property.targetMeta;
44
- if (items.length === 0) {
45
- return [];
46
- }
47
- field ??= targetMeta.compositePK ? targetMeta.primaryKeys : targetMeta.serializedPrimaryKey;
48
- const cb = (i, f) => {
49
- if (Utils.isEntity(i[f], true)) {
50
- return wrap(i[f], true).getPrimaryKey();
51
- }
52
- return i[f];
53
- };
54
- return items.map(i => {
55
- if (Array.isArray(field)) {
56
- return field.map(f => cb(i, f));
57
- }
58
- return cb(i, field);
59
- });
60
- }
61
- add(entity, ...entities) {
62
- entities = Utils.asArray(entity).concat(entities);
63
- for (const item of entities) {
64
- const entity = Reference.unwrapReference(item);
65
- if (!this.contains(entity, false)) {
66
- this.incrementCount(1);
67
- this[this.items.size] = entity;
68
- this.items.add(entity);
69
- this.propagate(entity, 'add');
70
- }
71
- }
72
- }
73
- /**
74
- * @internal
75
- */
76
- addWithoutPropagation(entity) {
77
- if (!this.contains(entity, false)) {
78
- this.incrementCount(1);
79
- this[this.items.size] = entity;
80
- this.items.add(entity);
81
- this.dirty = true;
82
- }
83
- }
84
- set(items) {
85
- if (!this.initialized) {
86
- this.initialized = true;
87
- this.snapshot = undefined;
88
- }
89
- if (this.compare(Utils.asArray(items).map(item => Reference.unwrapReference(item)))) {
90
- return;
91
- }
92
- this.remove(this.items);
93
- this.add(items);
94
- }
95
- compare(items) {
96
- if (items.length !== this.items.size) {
97
- return false;
98
- }
99
- let idx = 0;
100
- for (const item of this.items) {
101
- if (item !== items[idx++]) {
102
- return false;
103
- }
104
- }
105
- return true;
106
- }
107
- /**
108
- * @internal
109
- */
110
- hydrate(items, forcePropagate) {
111
- for (let i = 0; i < this.items.size; i++) {
112
- delete this[i];
113
- }
114
- this.initialized = true;
115
- this.items.clear();
116
- this._count = 0;
117
- this.add(items);
118
- this.takeSnapshot(forcePropagate);
119
- }
120
- /**
121
- * Remove specified item(s) from the collection. Note that removing item from collection does not necessarily imply deleting the target entity,
122
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
123
- * 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`,
124
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
125
- */
126
- remove(entity, ...entities) {
127
- entities = Utils.asArray(entity).concat(entities);
128
- let modified = false;
129
- for (const item of entities) {
130
- if (!item) {
131
- continue;
132
- }
133
- const entity = Reference.unwrapReference(item);
134
- if (this.items.delete(entity)) {
135
- this.incrementCount(-1);
136
- delete this[this.items.size]; // remove last item
137
- this.propagate(entity, 'remove');
138
- modified = true;
139
- }
140
- }
141
- if (modified) {
142
- Object.assign(this, [...this.items]); // reassign array access
143
- }
144
- }
145
- /**
146
- * Remove all items from the collection. Note that removing items from collection does not necessarily imply deleting the target entity,
147
- * it means we are disconnecting the relation - removing items from collection, not removing entities from database - `Collection.remove()`
148
- * 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`,
149
- * which tells the ORM we don't want orphaned entities to exist, so we know those should be removed.
150
- */
151
- removeAll() {
152
- if (!this.initialized) {
153
- this.initialized = true;
154
- this.snapshot = undefined;
155
- }
156
- this.remove(this.items);
157
- }
158
- /**
159
- * @internal
160
- */
161
- removeWithoutPropagation(entity) {
162
- if (!this.items.delete(entity)) {
163
- return;
164
- }
165
- this.incrementCount(-1);
166
- delete this[this.items.size];
167
- Object.assign(this, [...this.items]);
168
- this.dirty = true;
169
- }
170
- contains(item, check) {
171
- const entity = Reference.unwrapReference(item);
172
- return this.items.has(entity);
173
- }
174
- /**
175
- * Extracts a slice of the collection items starting at position start to end (exclusive) of the collection.
176
- * If end is null it returns all elements from start to the end of the collection.
177
- */
178
- slice(start = 0, end) {
179
- let index = 0;
180
- end ??= this.items.size;
181
- const items = [];
182
- for (const item of this.items) {
183
- if (index === end) {
184
- break;
185
- }
186
- if (index >= start && index < end) {
187
- items.push(item);
188
- }
189
- index++;
190
- }
191
- return items;
192
- }
193
- /**
194
- * Tests for the existence of an element that satisfies the given predicate.
195
- */
196
- exists(cb) {
197
- for (const item of this.items) {
198
- if (cb(item)) {
199
- return true;
200
- }
201
- }
202
- return false;
203
- }
204
- /**
205
- * Returns the first element of this collection that satisfies the predicate.
206
- */
207
- find(cb) {
208
- let index = 0;
209
- for (const item of this.items) {
210
- if (cb(item, index++)) {
211
- return item;
212
- }
213
- }
214
- return undefined;
215
- }
216
- /**
217
- * Extracts a subset of the collection items.
218
- */
219
- filter(cb) {
220
- const items = [];
221
- let index = 0;
222
- for (const item of this.items) {
223
- if (cb(item, index++)) {
224
- items.push(item);
225
- }
226
- }
227
- return items;
228
- }
229
- /**
230
- * Maps the collection items based on your provided mapper function.
231
- */
232
- map(mapper) {
233
- const items = [];
234
- let index = 0;
235
- for (const item of this.items) {
236
- items.push(mapper(item, index++));
237
- }
238
- return items;
239
- }
240
- /**
241
- * Maps the collection items based on your provided mapper function to a single object.
242
- */
243
- reduce(cb, initial = {}) {
244
- let index = 0;
245
- for (const item of this.items) {
246
- initial = cb(initial, item, index++);
247
- }
248
- return initial;
249
- }
250
- /**
251
- * Maps the collection items to a dictionary, indexed by the key you specify.
252
- * If there are more items with the same key, only the first one will be present.
253
- */
254
- indexBy(key, valueKey) {
255
- return this.reduce((obj, item) => {
256
- obj[item[key]] ??= valueKey ? item[valueKey] : item;
257
- return obj;
258
- }, {});
259
- }
260
- count() {
261
- return this.items.size;
262
- }
263
- isInitialized(fully = false) {
264
- if (!this.initialized || !fully) {
265
- return this.initialized;
266
- }
267
- for (const item of this.items) {
268
- if (!helper(item).__initialized) {
269
- return false;
270
- }
271
- }
272
- return true;
273
- }
274
- isDirty() {
275
- return this.dirty;
276
- }
277
- isEmpty() {
278
- return this.count() === 0;
279
- }
280
- setDirty(dirty = true) {
281
- this.dirty = dirty;
282
- }
283
- get length() {
284
- return this.count();
285
- }
286
- *[Symbol.iterator]() {
287
- for (const item of this.getItems()) {
288
- yield item;
289
- }
290
- }
291
- /**
292
- * @internal
293
- */
294
- takeSnapshot(forcePropagate) {
295
- this.snapshot = [...this.items];
296
- this.setDirty(false);
297
- if (this.property.owner || forcePropagate) {
298
- this.items.forEach(item => {
299
- this.propagate(item, 'takeSnapshot');
300
- });
301
- }
302
- }
303
- /**
304
- * @internal
305
- */
306
- getSnapshot() {
307
- return this.snapshot;
308
- }
309
- /**
310
- * @internal
311
- */
312
- get property() {
313
- if (!this._property) {
314
- const meta = wrap(this.owner, true).__meta;
315
- /* v8 ignore next 3 */
316
- if (!meta) {
317
- throw MetadataError.fromUnknownEntity(this.owner.constructor.name, 'Collection.property getter, maybe you just forgot to initialize the ORM?');
318
- }
319
- this._property = meta.relations.find(prop => this.owner[prop.name] === this);
320
- }
321
- return this._property;
322
- }
323
- /**
324
- * @internal
325
- */
326
- set property(prop) {
327
- this._property = prop;
328
- }
329
- propagate(item, method) {
330
- if (this.property.owner && this.property.inversedBy) {
331
- this.propagateToInverseSide(item, method);
332
- }
333
- else if (!this.property.owner && this.property.mappedBy) {
334
- this.propagateToOwningSide(item, method);
335
- }
336
- }
337
- propagateToInverseSide(item, method) {
338
- const collection = item[this.property.inversedBy];
339
- if (this.shouldPropagateToCollection(collection, method)) {
340
- method = method === 'takeSnapshot' ? method : (method + 'WithoutPropagation');
341
- collection[method](this.owner);
342
- }
343
- }
344
- propagateToOwningSide(item, method) {
345
- const mappedBy = this.property.mappedBy;
346
- const collection = item[mappedBy];
347
- if (this.property.kind === ReferenceKind.MANY_TO_MANY) {
348
- if (this.shouldPropagateToCollection(collection, method)) {
349
- collection[method](this.owner);
350
- }
351
- }
352
- else if (this.property.kind === ReferenceKind.ONE_TO_MANY && method !== 'takeSnapshot') {
353
- const prop2 = this.property.targetMeta.properties[mappedBy];
354
- const owner = prop2.mapToPk ? helper(this.owner).getPrimaryKey() : this.owner;
355
- const value = method === 'add' ? owner : null;
356
- if (this.property.orphanRemoval && method === 'remove') {
357
- // cache the PK before we propagate, as its value might be needed when flushing
358
- helper(item).__pk = helper(item).getPrimaryKey();
359
- }
360
- if (!prop2.nullable && prop2.deleteRule !== 'cascade' && method === 'remove') {
361
- if (!this.property.orphanRemoval) {
362
- throw ValidationError.cannotRemoveFromCollectionWithoutOrphanRemoval(this.owner, this.property);
363
- }
364
- return;
365
- }
366
- // skip if already propagated
367
- if (Reference.unwrapReference(item[mappedBy]) !== value) {
368
- item[mappedBy] = value;
369
- }
370
- }
371
- }
372
- shouldPropagateToCollection(collection, method) {
373
- if (!collection) {
374
- return false;
375
- }
376
- switch (method) {
377
- case 'add':
378
- return !collection.contains(this.owner, false);
379
- case 'remove':
380
- return collection.isInitialized() && collection.contains(this.owner, false);
381
- case 'takeSnapshot':
382
- return collection.isDirty();
383
- }
384
- }
385
- incrementCount(value) {
386
- if (typeof this._count === 'number' && this.initialized) {
387
- this._count += value;
388
- }
389
- }
390
- /** @ignore */
391
- [inspect.custom](depth = 2) {
392
- const object = { ...this };
393
- const hidden = ['items', 'owner', '_property', '_count', 'snapshot', '_populated', '_snapshot', '_lazyInitialized', '_em', 'readonly'];
394
- hidden.forEach(k => delete object[k]);
395
- const ret = inspect(object, { depth });
396
- const name = `${this.constructor.name}<${this.property?.type ?? 'unknown'}>`;
397
- return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
398
- }
399
- }
400
- Object.defineProperties(ArrayCollection.prototype, {
401
- __collection: { value: true, enumerable: false, writable: false },
402
- });
@@ -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) {
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
- }