Registry / database / moleculer-context-db

moleculer-context-db

JSON →
library2.0.3jsnpmunverified

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.

npm install moleculer-context-db
INSTALL
IMPORT
SIG · MOLECULER-CONTEXT-
M
moleculer-context-db
databasejavascriptv2.0.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MikroConnector
import { MikroConnector } from 'moleculer-context-db';
const MikroConnector = require('moleculer-context-db').MikroConnector;
Used to configure and initialize the Mikro-ORM connection. CommonJS `require` works but ES6 import is preferred.
DatabaseContextManager
import { DatabaseContextManager } from 'moleculer-context-db';
const DatabaseContextManager = require('moleculer-context-db').DatabaseContextManager;
Manages the database context and provides the Moleculer middleware. CommonJS `require` works but ES6 import is preferred.
middleware
yourMoleculerBroker.middlewares.add(DatabaseContextManager.middleware());
yourMoleculerBroker.middlewares.add(middleware());
The `middleware` method is a static method of `DatabaseContextManager` and should be called directly on the class.

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.

import { ServiceBroker } from 'moleculer'; import { MikroConnector, DatabaseContextManager } from 'moleculer-context-db'; import { BaseEntity, Entity, PrimaryKey, Property, MikroORM, Collection } from '@mikro-orm/core'; import { SqliteDriver } from '@mikro-orm/sqlite'; // 1. Define your Mikro-ORM entities (example) @Entity() class User extends BaseEntity<User, 'id'> { @PrimaryKey() id!: number; @Property({ unique: true }) username!: string; @Property() email!: string; } // 2. Instantiate and initialize the MikroConnector const connector = new MikroConnector<SqliteDriver>(); async function setup() { await connector.init({ type: 'sqlite', dbName: ':memory:', entities: [User], cache: { enabled: false }, // Ensure schema is synchronized for in-memory DB migrations: { runMigrations: true, path: './migrations' }, // Dummy path, not used for in-memory allowGlobalContext: true // Important for direct ORM access in tests/scripts }); const orm = connector.getOrm(); if (orm) { await orm.getSchemaGenerator().updateSchema(); } // 3. Create a Moleculer Service Broker const broker = new ServiceBroker({ logger: true, logLevel: 'info' }); // 4. Instantiate DatabaseContextManager and add its middleware const dbContextManager = new DatabaseContextManager(connector); broker.middlewares.add(dbContextManager.middleware()); // 5. Define a Moleculer service that uses the context-injected EntityManager broker.createService({ name: 'users', actions: { async create(ctx) { // Access the EntityManager from the context const em = ctx.em; if (!em) { throw new Error('EntityManager not found in context'); } const { username, email } = ctx.params; const user = em.create(User, { username, email }); await em.persistAndFlush(user); return user; }, async list(ctx) { const em = ctx.em; if (!em) { throw new Error('EntityManager not found in context'); } return em.find(User, {}); } } }); await broker.start(); // 6. Call a service action to test try { const user1 = await broker.call('users.create', { username: 'john.doe', email: 'john@example.com' }); console.log('Created user:', user1); const user2 = await broker.call('users.create', { username: 'jane.doe', email: 'jane@example.com' }); console.log('Created user:', user2); const users = await broker.call('users.list'); console.log('All users:', users); } catch (error) { console.error('Error during service call:', error); } finally { await broker.stop(); const orm = connector.getOrm(); if (orm) { await orm.close(); } } } setup();
Debug
Known issues
gotchaMongoDB 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.
fix
For production systems requiring MongoDB, comprehensive custom testing is recommended. Review the underlying Mikro-ORM documentation for specific MongoDB transaction behaviors and limitations.
affects: >=2.0.0
gotchaMoleculer 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.
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.
affects: >=2.0.0
gotchaWhen 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.
fix
For MongoDB replica sets, ensure your `MikroConnector.init()` configuration includes `implicitTransactions: true`.
affects: >=2.0.0
Errors
Common errors & fixes
Error: Cannot find module '@mikro-orm/core'
Mikro-ORM core package is a peer dependency but has not been installed.
fix
Install the core Mikro-ORM package: `npm install @mikro-orm/core`
Error: Cannot find module 'moleculer'
Moleculer is a peer dependency but has not been installed.
fix
Install the Moleculer framework: `npm install moleculer`
Error: Driver not found for type 'sqlite'
The specific Mikro-ORM database driver (e.g., `@mikro-orm/sqlite`) for the configured database type is missing.
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.
Error: EntityManager not found in context
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.
fix
Ensure `yourMoleculerBroker.middlewares.add(dbContextManager.middleware());` is called *before* starting the broker and calling actions.
Upgrade
Version history
2.0.3latest on npm
Audit
Dependencies
moleculerrequiredCore microservices framework that this library extends and integrates with.
@mikro-orm/corerequiredCore ORM library for database interactions; this package provides the context integration for Mikro-ORM.
@mikro-orm/mongodboptionalOptional driver for MongoDB support. Required if using MongoDB with Mikro-ORM.
@mikro-orm/sqliteoptionalOptional driver for SQLite support. Required if using SQLite with Mikro-ORM.
@mikro-orm/mysqloptionalOptional driver for MySQL support. Required if using MySQL with Mikro-ORM.
@mikro-orm/postgresqloptionalOptional driver for PostgreSQL support. Required if using PostgreSQL with Mikro-ORM.
Agent activity
4 hits · last 30 days
node
4
Resources
moleculer-context-db — npm install moleculer-context-db · libregistry