Skip to content

Commit

Permalink
fix(mikro): infinite loop when using OneToOne eager loading (#546)
Browse files Browse the repository at this point in the history
* fix(mikro): infinite loop when using OneToOne eager loading

* fix(mikro): mapping custom property of mikro entity to automapper
  • Loading branch information
zgid123 authored Jan 22, 2024
1 parent d92f62f commit ec00a0d
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions packages/mikro/src/lib/serialize-entity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isEmpty } from '@automapper/core';
import type { AnyEntity } from '@mikro-orm/core';
import { Reference, Utils, wrap } from '@mikro-orm/core';
import type { IWrappedEntityInternal } from '@mikro-orm/core/typings';

const excluded = [
'__gettersDefined',
Expand All @@ -14,13 +15,16 @@ const excluded = [
export function serializeEntity(
item: AnyEntity,
itemMetadata: Record<string, unknown> | undefined,
toPojo = false
toPojo = false,
memorized = new Map<AnyEntity, Record<string, unknown>>,
skipCheckExisting = false
) {
if (!Utils.isEntity(item)) return item;
if (toPojo) return wrap(item).toPOJO();

const result = {} as Record<string | symbol, unknown>;
for (const key of Reflect.ownKeys(item)) {
const keys = Object.keys((wrap(item) as IWrappedEntityInternal<AnyEntity>).__meta.properties);
for (const key of keys) {
if (typeof key === 'symbol' || excluded.includes(key)) {
continue;
}
Expand All @@ -33,30 +37,46 @@ export function serializeEntity(
return serializeEntity(
snapshot as AnyEntity,
keyMetadata,
true,
memorized,
true
);
});
continue;
}

if (Reference.isReference(value)) {
const isExisting = memorized.has(value);

if (!skipCheckExisting && isExisting) {
result[key] = memorized.get(value);
continue;
}

if (!value.isInitialized()) {
memorized.set(value, wrap(value).toPOJO());
result[key] = serializeEntity(
wrap(value).toPOJO(),
keyMetadata
keyMetadata,
false,
memorized,
!isExisting
);
continue;
}

memorized.set(value, value.getEntity() as Record<string, unknown>);
result[key] = serializeEntity(
value.getEntity(),
keyMetadata,
typeof keyMetadata === 'object' && isEmpty(keyMetadata)
typeof keyMetadata === 'object' && isEmpty(keyMetadata),
memorized,
!isExisting
);
continue;
}

result[key] = serializeEntity(value, keyMetadata);
result[key] = serializeEntity(value, keyMetadata, false, memorized, false);
}

if (result['id'] == null && item['id'] != null) {
Expand Down

0 comments on commit ec00a0d

Please sign in to comment.