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
muslnode 18–226 runs
build_error
glibcnode 18–226 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();
Errors
Common errors & fixes
Error: Cannot find module '@mikro-orm/core'
Mikro-ORM core package is a peer dependency but has not been installed.
fixInstall 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.
fixInstall 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.
fixInstall 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.
fixEnsure `yourMoleculerBroker.middlewares.add(dbContextManager.middleware());` is called *before* starting the broker and calling actions.
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.