Skip to content

Commit

Permalink
fix: defer automatic clear call on autoLoadEntities cache done on…
Browse files Browse the repository at this point in the history
… shutdown

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.
  • Loading branch information
B4nan committed Dec 23, 2023
1 parent 6d04209 commit 8b670eb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/mikro-orm-core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 16 additions & 0 deletions src/mikro-orm.entities.storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,16 @@ import type { EntityName } from './typings';
export class MikroOrmEntitiesStorage {

private static readonly storage = new Map<string, Set<EntityName<AnyEntity>>>();
private static shouldClear = false;

static addEntity(entity: EntityName<AnyEntity>, contextName = 'default') {
if (this.shouldClear) {
this.clear(contextName);
this.shouldClear = false;
}

let set = this.storage.get(contextName);

if (!set) {
set = new Set<EntityName<AnyEntity>>();
this.storage.set(contextName, set);
Expand All @@ -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;
}

}

0 comments on commit 8b670eb

Please sign in to comment.