{"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.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install moleculer-context-db"],"cli":null},"imports":["import { MikroConnector } from 'moleculer-context-db';","import { DatabaseContextManager } from 'moleculer-context-db';","yourMoleculerBroker.middlewares.add(DatabaseContextManager.middleware());"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}