57 lines
1.9 KiB
Plaintext
57 lines
1.9 KiB
Plaintext
export const metadata = {
|
||
title: `${pageNumber} Database Connection Loader`,
|
||
}
|
||
|
||
# {metadata.title}
|
||
|
||
In this document, you’ll learn about how to load the database connection in your module.
|
||
|
||
## Modules Database Connection
|
||
|
||
By default, a module will use the same database connection of the Medusa application.
|
||
|
||
To access those database credentials and ensure that MikroORM’s [entity](https://mikro-orm.io/docs/entity-manager) and [transaction](https://mikro-orm.io/docs/transactions) managers use those credentials when performing database operations, you must pass a database connection loader in your module’s definition.
|
||
|
||
Medusa provides a utility connection loader factory that handles registering the database options and entity and transaction managers into the module’s container.
|
||
|
||
---
|
||
|
||
## How to Add a Database Connection Loader?
|
||
|
||
In your module’s definition file, import the `ModulesSdkUtils` utility function from `@medusajs/utils`. Then, use its `mikroOrmConnectionLoaderFactory` function to create a connection loader and export it in the module’s definition.
|
||
|
||
For example:
|
||
|
||
```ts title="src/modules/hello/index.ts"
|
||
// other imports...
|
||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||
import { MyCustom } from "./models/my-custom"
|
||
|
||
const pathToMigrations = __dirname + "/migrations"
|
||
|
||
// ...
|
||
|
||
const connectionLoader = ModulesSdkUtils
|
||
.mikroOrmConnectionLoaderFactory({
|
||
moduleName,
|
||
moduleModels: [MyCustom],
|
||
migrationsPath: pathToMigrations,
|
||
})
|
||
|
||
export default {
|
||
// ...
|
||
loaders: [
|
||
// ...
|
||
connectionLoader,
|
||
],
|
||
}
|
||
```
|
||
|
||
The `mikroOrmConnectionLoaderFactory` function accepts an object with the following properties:
|
||
|
||
- `moduleName`: The name of the module.
|
||
- `moduleModules`: An array of data models in the module.
|
||
- `migrationsPath`: The path to the migrations file.
|
||
|
||
You can now implement data-management methods as explained in the next chapters.
|