{"id":16445,"library":"moleculer-context-db","title":"Moleculer Database Context Integrator","description":"moleculer-context-db is a utility library for Moleculer microservices that integrates database session management directly into the service context. It currently offers built-in support for Mikro-ORM, specifically focusing on providing transaction-safe database sessions for actions. While SQL databases have been thoroughly tested, MongoDB support is noted as experimental. The library streamlines the process of injecting a database EntityManager or session into each Moleculer action's context, ensuring that operations within an action can participate in a single, consistent transaction. The current stable version is 2.0.3. Release cadence is not explicitly stated but aligns with Mikro-ORM major versions due to peer dependencies. Its key differentiator is simplifying transaction management within a Moleculer microservice architecture, abstracting away manual session handling.","status":"active","version":"2.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/ujwal-setlur/moleculer-context-db","tags":["javascript","moleculer","microservices","database","session","transaction","typescript"],"install":[{"cmd":"npm install moleculer-context-db","lang":"bash","label":"npm"},{"cmd":"yarn add moleculer-context-db","lang":"bash","label":"yarn"},{"cmd":"pnpm add moleculer-context-db","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core microservices framework that this library extends and integrates with.","package":"moleculer","optional":false},{"reason":"Core ORM library for database interactions; this package provides the context integration for Mikro-ORM.","package":"@mikro-orm/core","optional":false},{"reason":"Optional driver for MongoDB support. Required if using MongoDB with Mikro-ORM.","package":"@mikro-orm/mongodb","optional":true},{"reason":"Optional driver for SQLite support. Required if using SQLite with Mikro-ORM.","package":"@mikro-orm/sqlite","optional":true},{"reason":"Optional driver for MySQL support. Required if using MySQL with Mikro-ORM.","package":"@mikro-orm/mysql","optional":true},{"reason":"Optional driver for PostgreSQL support. Required if using PostgreSQL with Mikro-ORM.","package":"@mikro-orm/postgresql","optional":true}],"imports":[{"note":"Used to configure and initialize the Mikro-ORM connection. CommonJS `require` works but ES6 import is preferred.","wrong":"const MikroConnector = require('moleculer-context-db').MikroConnector;","symbol":"MikroConnector","correct":"import { MikroConnector } from 'moleculer-context-db';"},{"note":"Manages the database context and provides the Moleculer middleware. CommonJS `require` works but ES6 import is preferred.","wrong":"const DatabaseContextManager = require('moleculer-context-db').DatabaseContextManager;","symbol":"DatabaseContextManager","correct":"import { DatabaseContextManager } from 'moleculer-context-db';"},{"note":"The `middleware` method is a static method of `DatabaseContextManager` and should be called directly on the class.","wrong":"yourMoleculerBroker.middlewares.add(middleware());","symbol":"middleware","correct":"yourMoleculerBroker.middlewares.add(DatabaseContextManager.middleware());"}],"quickstart":{"code":"import { ServiceBroker } from 'moleculer';\nimport { MikroConnector, DatabaseContextManager } from 'moleculer-context-db';\nimport { BaseEntity, Entity, PrimaryKey, Property, MikroORM, Collection } from '@mikro-orm/core';\nimport { SqliteDriver } from '@mikro-orm/sqlite';\n\n// 1. Define your Mikro-ORM entities (example)\n@Entity()\nclass User extends BaseEntity<User, 'id'> {\n  @PrimaryKey()\n  id!: number;\n\n  @Property({ unique: true })\n  username!: string;\n\n  @Property()\n  email!: string;\n}\n\n// 2. Instantiate and initialize the MikroConnector\nconst connector = new MikroConnector<SqliteDriver>();\n\nasync function setup() {\n  await connector.init({\n    type: 'sqlite',\n    dbName: ':memory:',\n    entities: [User],\n    cache: { enabled: false },\n    // Ensure schema is synchronized for in-memory DB\n    migrations: { runMigrations: true, path: './migrations' }, // Dummy path, not used for in-memory\n    allowGlobalContext: true // Important for direct ORM access in tests/scripts\n  });\n  const orm = connector.getOrm();\n  if (orm) {\n    await orm.getSchemaGenerator().updateSchema();\n  }\n\n  // 3. Create a Moleculer Service Broker\n  const broker = new ServiceBroker({\n    logger: true,\n    logLevel: 'info'\n  });\n\n  // 4. Instantiate DatabaseContextManager and add its middleware\n  const dbContextManager = new DatabaseContextManager(connector);\n  broker.middlewares.add(dbContextManager.middleware());\n\n  // 5. Define a Moleculer service that uses the context-injected EntityManager\n  broker.createService({\n    name: 'users',\n    actions: {\n      async create(ctx) {\n        // Access the EntityManager from the context\n        const em = ctx.em;\n        if (!em) {\n          throw new Error('EntityManager not found in context');\n        }\n        const { username, email } = ctx.params;\n        const user = em.create(User, { username, email });\n        await em.persistAndFlush(user);\n        return user;\n      },\n      async list(ctx) {\n        const em = ctx.em;\n        if (!em) {\n            throw new Error('EntityManager not found in context');\n        }\n        return em.find(User, {});\n      }\n    }\n  });\n\n  await broker.start();\n\n  // 6. Call a service action to test\n  try {\n    const user1 = await broker.call('users.create', { username: 'john.doe', email: 'john@example.com' });\n    console.log('Created user:', user1);\n\n    const user2 = await broker.call('users.create', { username: 'jane.doe', email: 'jane@example.com' });\n    console.log('Created user:', user2);\n\n    const users = await broker.call('users.list');\n    console.log('All users:', users);\n  } catch (error) {\n    console.error('Error during service call:', error);\n  } finally {\n    await broker.stop();\n    const orm = connector.getOrm();\n    if (orm) {\n      await orm.close();\n    }\n  }\n}\n\nsetup();\n","lang":"typescript","description":"Demonstrates how to set up moleculer-context-db with Mikro-ORM (SQLite) in a Moleculer broker, define an entity, and perform CRUD operations within a service using the context-injected EntityManager."},"warnings":[{"fix":"For production systems requiring MongoDB, comprehensive custom testing is recommended. Review the underlying Mikro-ORM documentation for specific MongoDB transaction behaviors and limitations.","message":"MongoDB support is considered experimental and has not been as thoroughly tested as SQL database integrations. Users relying on MongoDB should proceed with caution and thorough testing.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Ensure you install `moleculer`, `@mikro-orm/core`, and the specific Mikro-ORM driver(s) (e.g., `@mikro-orm/sqlite`, `@mikro-orm/mongodb`) that match the versions specified in your project's `package.json` or the library's peer dependency range.","message":"Moleculer and Mikro-ORM (specifically `@mikro-orm/core` and specific drivers like `@mikro-orm/sqlite`) are peer dependencies. They must be installed separately in your project, and version compatibility should be checked.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"For MongoDB replica sets, ensure your `MikroConnector.init()` configuration includes `implicitTransactions: true`.","message":"When configuring MikroConnector for MongoDB, `implicitTransactions` must be set to `true` if you require transaction support and are running a replica set. Failing to do so might result in transaction-related errors.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Install the core Mikro-ORM package: `npm install @mikro-orm/core`","cause":"Mikro-ORM core package is a peer dependency but has not been installed.","error":"Error: Cannot find module '@mikro-orm/core'"},{"fix":"Install the Moleculer framework: `npm install moleculer`","cause":"Moleculer is a peer dependency but has not been installed.","error":"Error: Cannot find module 'moleculer'"},{"fix":"Install the appropriate Mikro-ORM driver for your database type, e.g., `npm install @mikro-orm/sqlite` for SQLite, or `@mikro-orm/mongodb` for MongoDB.","cause":"The specific Mikro-ORM database driver (e.g., `@mikro-orm/sqlite`) for the configured database type is missing.","error":"Error: Driver not found for type 'sqlite'"},{"fix":"Ensure `yourMoleculerBroker.middlewares.add(dbContextManager.middleware());` is called *before* starting the broker and calling actions.","cause":"The `DatabaseContextManager.middleware()` was not correctly added to the Moleculer broker, or the action was called without a context where the EntityManager would be injected.","error":"Error: EntityManager not found in context"}],"ecosystem":"npm"}