A database tool for providing the database session as part of the context
npm install moleculer-context-dbA database integrator for injecting a transaction safe database session into the
context of the action. Currently, this only has built in support for Mikro-ORM, and in that only SQL databases have been tested. Mongo support is experimental.
To install with npm
``shell script`
npm install moleculer-context-db
moleculer and @mikro-orm/core are peer dependecies and need to be installed separately.
ES6 style
`js`
import { MikroConnector, DatabaseContextManager } from 'moleculer-context-db';
CommonJS
`js`
const {
MikroConnector,
DatabaseContextManager
} = require('moleculer-context-db');
You can create a new MikroConnector as such
`js`
const connector = new MikroConnector();
You will also need to install the appropriate database driver, e.g.:
`js
import {MongoDriver} from '@mikro-orm/mongodb';
const connector = new MikroConnector
`
or
`js
npm i @mikro-orm/sqlite;
const connector = new MikroConnector();
`
You will then need to initialize the connector
`js`
await connector.init({
type: 'sqlite', // or use 'mongo' for mongodb
dbName: ':memory',
entities: [YourEntity1, YourEntity2],
cache: {
enabled: false
}
});
For mongo support, you will need to do:
`js`
await connector.init({
type: 'mongo', // or use 'mongo' for mongodb
dbName:
clientUrl:
entities: [YourEntity1, YourEntity2],
cache: {
enabled: false
},
implicitTransactions:
});
You can use all available options for MikroORM.init()
To use, simply instantiate a DatabaseContextManager with the connector and then add
the result of the middleware method to your broker's middleware
`javascript
const dbContextManager: DatabaseContextManager = new DatabaseContextManager(
connector
);
yourMoleculerBroker.middlewares.add(DatabaseContextManager.middleware());
``
The above statement will wrap all local actions with a Mikro-ORM transaction.