Skip to content

[Fix] Global EntityManager Context Issue in Mikro ORM Configuration #8700

Open
@rahul-rocket

Description

@rahul-rocket

Description:

The allowGlobalContext configuration is causing issues during the API Core startup when using Mikro ORM. Specifically, the error occurs because the global EntityManager is being used for context-specific actions, which is disallowed. This issue is severe as it could be contributing to performance problems in the project.

Error during API Core startup: ValidationError: Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead.
    at Function.cannotUseGlobalContext (D:\ever-co\ever-gauzy\node_modules\@mikro-orm\core\errors.js:96:16)
    at SqlEntityManager.getContext (D:\ever-co\ever-gauzy\node_modules\@mikro-orm\core\EntityManager.js:1450:44)
    at SqlEntityManager.tryFlush (D:\ever-co\ever-gauzy\node_modules\@mikro-orm\core\EntityManager.js:1321:25)
    at SqlEntityManager.count (D:\ever-co\ever-gauzy\node_modules\@mikro-orm\core\EntityManager.js:1230:18)
    at MikroOrmUserRepository.count (D:\ever-co\ever-gauzy\node_modules\@mikro-orm\core\entity\EntityRepository.js:191:40)
    at UserService.count (D:\ever-co\ever-gauzy\packages\core\src\lib\core\crud\crud.service.ts42)
    at UserService.countFast (D:\ever-co\ever-gauzy\packages\core\src\lib\core\crud\tenant-aware-crud.service.ts:180:22)
    at AppService.seedDBIfEmpty (D:\ever-co\ever-gauzy\packages\core\src\lib\app\app.service.ts:27:39)
    at bootstrap (D:\ever-co\ever-gauzy\packages\core\src\lib\bootstrap\index.ts:263:16)
    at async D:\ever-co\ever-gauzy\packages\core\src\lib\main.ts:26:9 {
  entity: undefined
}

Steps to Reproduce:

  1. Select mikro-orm as the ORM type into .env.
  2. Start the API Core service using yarn start:api:core command.
  3. Observe the error during the startup process.

Temporary Fix Attempted:

The allowGlobalContext: true option was temporarily applied to resolve the issue. However, it was reverted because:

Enabling the global context is not recommended for production.
It can lead to context-related issues.

Root Cause:
The project is using the global EntityManager for context-specific actions instead of using fork() or providing a scoped EntityManager instance.

Proposed Solution:

  1. Refactor the codebase to ensure that context-specific actions use a scoped EntityManager instance created via fork().
  2. Avoid using allowGlobalContext in the Mikro ORM configuration.
  3. Audit and update all services and repositories to correctly use a scoped EntityManager.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions