diff --git a/src/mikro-orm-core.module.ts b/src/mikro-orm-core.module.ts index e7d6fe3..f12b47f 100644 --- a/src/mikro-orm-core.module.ts +++ b/src/mikro-orm-core.module.ts @@ -112,7 +112,7 @@ export class MikroOrmCoreModule implements OnApplicationShutdown { if (orm) { await orm.close(); - MikroOrmEntitiesStorage.clear(orm.config.get('contextName')); + MikroOrmEntitiesStorage.clearLater(); } CONTEXT_NAMES.length = 0; diff --git a/src/mikro-orm.entities.storage.ts b/src/mikro-orm.entities.storage.ts index 9ee994d..d435ef6 100644 --- a/src/mikro-orm.entities.storage.ts +++ b/src/mikro-orm.entities.storage.ts @@ -4,9 +4,16 @@ import type { EntityName } from './typings'; export class MikroOrmEntitiesStorage { private static readonly storage = new Map>>(); + private static shouldClear = false; static addEntity(entity: EntityName, contextName = 'default') { + if (this.shouldClear) { + this.clear(contextName); + this.shouldClear = false; + } + let set = this.storage.get(contextName); + if (!set) { set = new Set>(); this.storage.set(contextName, set); @@ -23,4 +30,13 @@ export class MikroOrmEntitiesStorage { this.storage.get(contextName)?.clear(); } + /** + * When the `addEntity` is called next, the storage will be cleared automatically before it. + * We want to keep the cache, as it's populated on require time, but sometimes (tests) the contexts could be cleared. + * This resolves both cases by deferring the `clear` call to the first `addEntity` call. + */ + static clearLater() { + this.shouldClear = true; + } + }