@mikro-orm/nestjs 6.0.2 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -111,6 +111,27 @@ export class PhotoService {
111
111
  }
112
112
  ```
113
113
 
114
+ ## Driver-specific imports
115
+
116
+ When you try to inject the `EntityManager` or `MikroORM` symbols exported from the driver package, Nest.js needs to be aware of those typed. In other words, those driver specific exports need to be specifically registered in the DI container. This module uses automated discovery of the driver type in order to do that, but it fails to work when you use `useFactory` which requires some dependencies.
117
+
118
+ Instead of relying on this discovery, you can provide the driver type explicitly:
119
+
120
+ ```typescript
121
+ @Module({
122
+ imports: [
123
+ MikroOrmModule.forRootAsync({
124
+ useFactory: (configService: ConfigService) => configService.getOrThrow(ConfigKey.ORM),
125
+ inject: [ConfigService],
126
+ driver: PostgreSqlDriver,
127
+ }),
128
+ ],
129
+ controllers: [AppController],
130
+ providers: [AppService],
131
+ })
132
+ export class AppModule {}
133
+ ```
134
+
114
135
  ## Auto entities automatically
115
136
 
116
137
  Manually adding entities to the entities array of the connection options can be
@@ -255,6 +276,7 @@ export class AppModule {}
255
276
  Or, if you're using the Async provider:
256
277
  ```typescript
257
278
  import { Scope } from '@nestjs/common';
279
+ import { PostgreSqlDriver } from '@mikro-orm/postgresql';
258
280
 
259
281
  @Module({
260
282
  imports: [
@@ -342,7 +364,7 @@ More information about [enableShutdownHooks](https://docs.nestjs.com/fundamental
342
364
 
343
365
  ## Multiple Database Connections
344
366
 
345
- You can define multiple database connections by registering multiple `MikroOrmModule` and setting their `contextName`. If you want to use middleware request context you must disable automatic middleware and register `MikroOrmModule` with `forMiddleware()` or use NestJS `Injection Scope`
367
+ You can define multiple database connections by registering multiple `MikroOrmModule`'s, each with a unique `contextName`. You will need to disable the automatic request context middleware by setting `registerRequestContext` to `false`, as it wouldn't work with this approach - note that this needs to be part of all your `MikroOrmModule`s with non-default `contextName`. To have the same automatic request context behaviour, you must register `MikroOrmModule` with `forMiddleware()` instead:
346
368
 
347
369
  ```typescript
348
370
  @Module({
@@ -365,6 +387,21 @@ You can define multiple database connections by registering multiple `MikroOrmMo
365
387
  export class AppModule {}
366
388
  ```
367
389
 
390
+ Since MikroORM v6.4, you can also define [multiple configurations](https://mikro-orm.io/docs/quick-start#configuration-file-structure) as part of a single ORM config. If you want to use such a combined config file, you need to destructure the result, since it will be also an array:
391
+
392
+ ```typescript
393
+ @Module({
394
+ imports: [
395
+ // `config` exports an array of configs
396
+ ...MikroOrmModule.forRoot(config),
397
+ MikroOrmModule.forMiddleware()
398
+ ],
399
+ controllers: [AppController],
400
+ providers: [AppService],
401
+ })
402
+ export class AppModule {}
403
+ ```
404
+
368
405
  To access different `MikroORM`/`EntityManager` connections you have to use the new injection tokens `@InjectMikroORM()`/`@InjectEntityManager()` where you are required to pass the `contextName` in:
369
406
 
370
407
  ```ts
@@ -407,6 +444,17 @@ export class PhotoService {
407
444
  }
408
445
  ```
409
446
 
447
+ You can use the `@InjectMikroORMs` decorator to get all registered MikroORM instances:
448
+
449
+ ```typescript
450
+ @Injectable()
451
+ export class MyService {
452
+
453
+ constructor(@InjectMikroORMs() private readonly orms: MikroORM[]) { }
454
+
455
+ }
456
+ ```
457
+
410
458
  ## Testing
411
459
 
412
460
  The `nestjs-mikro-orm` package exposes `getRepositoryToken()` function that returns prepared token based on a given entity to allow mocking the repository.
@@ -1,3 +1,3 @@
1
1
  import type { MikroOrmMiddlewareModuleOptions } from './typings';
2
- import type { MiddlewareConsumer } from '@nestjs/common';
2
+ import { type MiddlewareConsumer } from '@nestjs/common';
3
3
  export declare function forRoutesPath(options: MikroOrmMiddlewareModuleOptions, consumer: MiddlewareConsumer): string;
@@ -1,14 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.forRoutesPath = void 0;
3
+ exports.forRoutesPath = forRoutesPath;
4
+ const common_1 = require("@nestjs/common");
4
5
  function forRoutesPath(options, consumer) {
5
- const isNestMiddleware = (consumer) => {
6
- return typeof consumer.httpAdapter === 'object';
7
- };
8
- const usingFastify = (consumer) => {
6
+ if (options.forRoutesPath) {
7
+ return options.forRoutesPath;
8
+ }
9
+ // detect nest v11 based on a newly added enum value
10
+ if (common_1.HttpStatus.MULTI_STATUS) {
11
+ return '{*all}';
12
+ }
13
+ const isFastify = (consumer) => {
14
+ if (typeof consumer.httpAdapter !== 'object') {
15
+ return false;
16
+ }
9
17
  return consumer.httpAdapter.constructor.name.toLowerCase().startsWith('fastify');
10
18
  };
11
- return options.forRoutesPath ??
12
- (isNestMiddleware(consumer) && usingFastify(consumer) ? '(.*)' : '*');
19
+ return isFastify(consumer) ? '(.*)' : '*';
13
20
  }
14
- exports.forRoutesPath = forRoutesPath;
@@ -1,7 +1,7 @@
1
- import { type DynamicModule, type MiddlewareConsumer, type OnApplicationShutdown } from '@nestjs/common';
1
+ import { type DynamicModule, type MiddlewareConsumer, type NestModule, type OnApplicationShutdown } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
3
  import { MikroOrmModuleOptions, type MikroOrmModuleAsyncOptions, type MikroOrmModuleSyncOptions } from './typings';
4
- export declare class MikroOrmCoreModule implements OnApplicationShutdown {
4
+ export declare class MikroOrmCoreModule implements NestModule, OnApplicationShutdown {
5
5
  private readonly options;
6
6
  private readonly moduleRef;
7
7
  constructor(options: MikroOrmModuleOptions, moduleRef: ModuleRef);
@@ -21,13 +21,23 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
21
21
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
22
  return c > 3 && r && Object.defineProperty(target, key, r), r;
23
23
  };
24
- var __importStar = (this && this.__importStar) || function (mod) {
25
- if (mod && mod.__esModule) return mod;
26
- var result = {};
27
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
- __setModuleDefault(result, mod);
29
- return result;
30
- };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
31
41
  var __metadata = (this && this.__metadata) || function (k, v) {
32
42
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
43
  };
@@ -71,6 +81,28 @@ let MikroOrmCoreModule = MikroOrmCoreModule_1 = class MikroOrmCoreModule {
71
81
  }
72
82
  static async forRoot(options) {
73
83
  const contextName = this.setContextName(options?.contextName);
84
+ if (options?.driver && !contextName) {
85
+ const packageName = PACKAGES[options.driver.name];
86
+ const driverPackage = await tryRequire(packageName);
87
+ if (driverPackage) {
88
+ return {
89
+ module: MikroOrmCoreModule_1,
90
+ providers: [
91
+ { provide: mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS, useValue: options || {} },
92
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName),
93
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName, driverPackage.MikroORM),
94
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, core_1.EntityManager),
95
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, driverPackage.EntityManager),
96
+ ],
97
+ exports: [
98
+ core_1.MikroORM,
99
+ core_1.EntityManager,
100
+ driverPackage.EntityManager,
101
+ driverPackage.MikroORM,
102
+ ],
103
+ };
104
+ }
105
+ }
74
106
  const knex = await tryRequire('@mikro-orm/knex');
75
107
  const mongo = await tryRequire('@mikro-orm/mongodb');
76
108
  const em = await this.createEntityManager(options);
@@ -118,6 +150,30 @@ let MikroOrmCoreModule = MikroOrmCoreModule_1 = class MikroOrmCoreModule {
118
150
  }
119
151
  static async forRootAsync(options) {
120
152
  const contextName = this.setContextName(options?.contextName);
153
+ if (options?.driver && !contextName) {
154
+ const packageName = PACKAGES[options.driver.name];
155
+ const driverPackage = await tryRequire(packageName);
156
+ if (driverPackage) {
157
+ return {
158
+ module: MikroOrmCoreModule_1,
159
+ imports: options.imports || [],
160
+ providers: [
161
+ ...(options.providers || []),
162
+ ...(0, mikro_orm_providers_1.createAsyncProviders)({ ...options, contextName: options.contextName }),
163
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName),
164
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName, driverPackage.MikroORM),
165
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, core_1.EntityManager),
166
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, driverPackage.EntityManager),
167
+ ],
168
+ exports: [
169
+ core_1.MikroORM,
170
+ core_1.EntityManager,
171
+ driverPackage.EntityManager,
172
+ driverPackage.MikroORM,
173
+ ],
174
+ };
175
+ }
176
+ }
121
177
  const knex = await tryRequire('@mikro-orm/knex');
122
178
  const mongo = await tryRequire('@mikro-orm/mongodb');
123
179
  const em = await this.createEntityManager(options);
@@ -192,7 +248,10 @@ let MikroOrmCoreModule = MikroOrmCoreModule_1 = class MikroOrmCoreModule {
192
248
  return config?.getDriver().createEntityManager();
193
249
  }
194
250
  catch {
195
- // ignore
251
+ if (options && 'useFactory' in options && 'inject' in options && options.inject.length > 0) {
252
+ // eslint-disable-next-line no-console
253
+ console.warn('Support for driver specific imports in modules defined with `useFactory` and `inject` requires an explicit `driver` option. See https://github.com/mikro-orm/nestjs/pull/204');
254
+ }
196
255
  }
197
256
  }
198
257
  async onApplicationShutdown() {
@@ -1,10 +1,10 @@
1
- import { type MiddlewareConsumer } from '@nestjs/common';
1
+ import { type MiddlewareConsumer, type NestModule } from '@nestjs/common';
2
2
  import type { MikroORM } from '@mikro-orm/core';
3
3
  import { MikroOrmMiddlewareModuleOptions } from './typings';
4
- export declare class MikroOrmMiddlewareModule {
4
+ export declare class MikroOrmMiddlewareModule implements NestModule {
5
5
  private readonly options;
6
6
  constructor(options: MikroOrmMiddlewareModuleOptions);
7
- static forMiddleware(options?: MikroOrmMiddlewareModuleOptions): {
7
+ static forRoot(options?: MikroOrmMiddlewareModuleOptions): {
8
8
  module: typeof MikroOrmMiddlewareModule;
9
9
  providers: ({
10
10
  provide: symbol;
@@ -22,10 +22,7 @@ let MikroOrmMiddlewareModule = MikroOrmMiddlewareModule_1 = class MikroOrmMiddle
22
22
  constructor(options) {
23
23
  this.options = options;
24
24
  }
25
- static forMiddleware(options) {
26
- // Work around due to nestjs not supporting the ability to register multiple types
27
- // https://github.com/nestjs/nest/issues/770
28
- // https://github.com/nestjs/nest/issues/4786#issuecomment-755032258 - workaround suggestion
25
+ static forRoot(options) {
29
26
  const inject = mikro_orm_common_1.CONTEXT_NAMES.map(name => (0, mikro_orm_common_1.getMikroORMToken)(name));
30
27
  return {
31
28
  module: MikroOrmMiddlewareModule_1,
@@ -3,9 +3,50 @@ import type { EntityName } from './typings';
3
3
  export declare const MIKRO_ORM_MODULE_OPTIONS: unique symbol;
4
4
  export declare const CONTEXT_NAMES: string[];
5
5
  export declare const logger: Logger;
6
+ /**
7
+ * Gets the injection token based on context name for the relevant MikroORM provider.
8
+ * @param name The context name of the database connection.
9
+ * @returns The MikroORM provider injection token for the supplied context name.
10
+ */
6
11
  export declare const getMikroORMToken: (name: string) => string;
12
+ /**
13
+ * Injects a MikroORM provider based on the supplied context name.
14
+ *
15
+ * @param name The context name of the database connection.
16
+ * @returns A parameter decorator which will cause NestJS to inject the relevant MikroORM provider.
17
+ */
7
18
  export declare const InjectMikroORM: (name: string) => PropertyDecorator & ParameterDecorator;
19
+ /**
20
+ * Injects the MikroORMs provider.
21
+ *
22
+ * @returns A decorator which will cause NestJS to inject the MikroORMs provider.
23
+ */
24
+ export declare const InjectMikroORMs: () => PropertyDecorator & ParameterDecorator;
25
+ /**
26
+ * Gets the injection token based on context name for the relevant EntityManager provider.
27
+ * @param name The context name of the database connection.
28
+ * @returns The EntityManager provider injection token for the supplied context name.
29
+ */
8
30
  export declare const getEntityManagerToken: (name: string) => string;
31
+ /**
32
+ * Injects an EntityManager provider based on the supplied context name.
33
+ *
34
+ * @param name The context name of the database connection.
35
+ * @returns A parameter decorator which will cause NestJS to inject the relevant EntityManager provider.
36
+ */
9
37
  export declare const InjectEntityManager: (name: string) => PropertyDecorator & ParameterDecorator;
38
+ /**
39
+ * Gets the injection token based on class and optionally based on context name.
40
+ * @param entity The class of the Entity to use for the injected repository provider.
41
+ * @param name An optional context name - required for multiple database connections. See: [Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
42
+ * @returns The EntityRepository provider injection token based on the supplied entity and context name.
43
+ */
10
44
  export declare const getRepositoryToken: <T extends object>(entity: EntityName<T>, name?: string) => string;
45
+ /**
46
+ * Injects an EntityRepository provider.
47
+ *
48
+ * @param entity The class of the Entity to use for the injected repository provider.
49
+ * @param name An optional context name - required for multiple database connections. See: [Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
50
+ * @returns A parameter decorator which will cause NestJS to inject the relevant EntityRepository provider.
51
+ */
11
52
  export declare const InjectRepository: <T extends object>(entity: EntityName<T>, name?: string) => PropertyDecorator & ParameterDecorator;
@@ -1,23 +1,65 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InjectRepository = exports.getRepositoryToken = exports.InjectEntityManager = exports.getEntityManagerToken = exports.InjectMikroORM = exports.getMikroORMToken = exports.logger = exports.CONTEXT_NAMES = exports.MIKRO_ORM_MODULE_OPTIONS = void 0;
3
+ exports.InjectRepository = exports.getRepositoryToken = exports.InjectEntityManager = exports.getEntityManagerToken = exports.InjectMikroORMs = exports.InjectMikroORM = exports.getMikroORMToken = exports.logger = exports.CONTEXT_NAMES = exports.MIKRO_ORM_MODULE_OPTIONS = void 0;
4
4
  const core_1 = require("@mikro-orm/core");
5
5
  const common_1 = require("@nestjs/common");
6
6
  exports.MIKRO_ORM_MODULE_OPTIONS = Symbol('mikro-orm-module-options');
7
7
  exports.CONTEXT_NAMES = [];
8
8
  exports.logger = new common_1.Logger(core_1.MikroORM.name);
9
+ /**
10
+ * Gets the injection token based on context name for the relevant MikroORM provider.
11
+ * @param name The context name of the database connection.
12
+ * @returns The MikroORM provider injection token for the supplied context name.
13
+ */
9
14
  const getMikroORMToken = (name) => `${name}_MikroORM`;
10
15
  exports.getMikroORMToken = getMikroORMToken;
16
+ /**
17
+ * Injects a MikroORM provider based on the supplied context name.
18
+ *
19
+ * @param name The context name of the database connection.
20
+ * @returns A parameter decorator which will cause NestJS to inject the relevant MikroORM provider.
21
+ */
11
22
  const InjectMikroORM = (name) => (0, common_1.Inject)((0, exports.getMikroORMToken)(name));
12
23
  exports.InjectMikroORM = InjectMikroORM;
24
+ /**
25
+ * Injects the MikroORMs provider.
26
+ *
27
+ * @returns A decorator which will cause NestJS to inject the MikroORMs provider.
28
+ */
29
+ const InjectMikroORMs = () => (0, common_1.Inject)('MikroORMs');
30
+ exports.InjectMikroORMs = InjectMikroORMs;
31
+ /**
32
+ * Gets the injection token based on context name for the relevant EntityManager provider.
33
+ * @param name The context name of the database connection.
34
+ * @returns The EntityManager provider injection token for the supplied context name.
35
+ */
13
36
  const getEntityManagerToken = (name) => `${name}_EntityManager`;
14
37
  exports.getEntityManagerToken = getEntityManagerToken;
38
+ /**
39
+ * Injects an EntityManager provider based on the supplied context name.
40
+ *
41
+ * @param name The context name of the database connection.
42
+ * @returns A parameter decorator which will cause NestJS to inject the relevant EntityManager provider.
43
+ */
15
44
  const InjectEntityManager = (name) => (0, common_1.Inject)((0, exports.getEntityManagerToken)(name));
16
45
  exports.InjectEntityManager = InjectEntityManager;
46
+ /**
47
+ * Gets the injection token based on class and optionally based on context name.
48
+ * @param entity The class of the Entity to use for the injected repository provider.
49
+ * @param name An optional context name - required for multiple database connections. See: [Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
50
+ * @returns The EntityRepository provider injection token based on the supplied entity and context name.
51
+ */
17
52
  const getRepositoryToken = (entity, name) => {
18
53
  const suffix = name ? `_${name}` : '';
19
54
  return `${core_1.Utils.className(entity)}Repository${suffix}`;
20
55
  };
21
56
  exports.getRepositoryToken = getRepositoryToken;
57
+ /**
58
+ * Injects an EntityRepository provider.
59
+ *
60
+ * @param entity The class of the Entity to use for the injected repository provider.
61
+ * @param name An optional context name - required for multiple database connections. See: [Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
62
+ * @returns A parameter decorator which will cause NestJS to inject the relevant EntityRepository provider.
63
+ */
22
64
  const InjectRepository = (entity, name) => (0, common_1.Inject)((0, exports.getRepositoryToken)(entity, name));
23
65
  exports.InjectRepository = InjectRepository;
@@ -4,7 +4,7 @@ export declare class MikroOrmEntitiesStorage {
4
4
  private static readonly storage;
5
5
  private static shouldClear;
6
6
  static addEntity(entity: EntityName<AnyEntity>, contextName?: string): void;
7
- static getEntities(contextName?: string): never[] | IterableIterator<EntityName<Partial<any>>>;
7
+ static getEntities(contextName?: string): never[] | SetIterator<EntityName<Partial<any>>>;
8
8
  static clear(contextName?: string): void;
9
9
  /**
10
10
  * When the `addEntity` is called next, the storage will be cleared automatically before it.
@@ -1,14 +1,16 @@
1
1
  import { type AnyEntity } from '@mikro-orm/core';
2
2
  import { type DynamicModule } from '@nestjs/common';
3
- import type { EntityName, MikroOrmMiddlewareModuleOptions, MikroOrmModuleAsyncOptions, MikroOrmModuleFeatureOptions, MikroOrmModuleSyncOptions } from './typings';
3
+ import { EntityName, MikroOrmModuleAsyncOptions, MikroOrmModuleFeatureOptions, MikroOrmModuleSyncOptions, MikroOrmMiddlewareModuleOptions, MaybePromise } from './typings';
4
4
  export declare class MikroOrmModule {
5
5
  /**
6
6
  * Clears the entity storage. This is useful for testing purposes, when you want to isolate the tests.
7
7
  * Keep in mind that this should be called when using a test runner that keeps the context alive between tests (like Vitest with threads disabled).
8
8
  */
9
9
  static clearStorage(contextName?: string): void;
10
- static forRoot(options?: MikroOrmModuleSyncOptions): DynamicModule;
11
- static forRootAsync(options: MikroOrmModuleAsyncOptions): DynamicModule;
10
+ static forRoot(options?: MikroOrmModuleSyncOptions): MaybePromise<DynamicModule>;
11
+ static forRoot(options?: MikroOrmModuleSyncOptions[]): MaybePromise<DynamicModule>[];
12
+ static forRootAsync(options: MikroOrmModuleAsyncOptions): MaybePromise<DynamicModule>;
13
+ static forRootAsync(options: MikroOrmModuleAsyncOptions[]): MaybePromise<DynamicModule>[];
12
14
  static forFeature(options: EntityName<AnyEntity>[] | MikroOrmModuleFeatureOptions, contextName?: string): DynamicModule;
13
15
  static forMiddleware(options?: MikroOrmMiddlewareModuleOptions): DynamicModule;
14
16
  }
@@ -23,16 +23,16 @@ let MikroOrmModule = MikroOrmModule_1 = class MikroOrmModule {
23
23
  mikro_orm_entities_storage_1.MikroOrmEntitiesStorage.clear(contextName);
24
24
  }
25
25
  static forRoot(options) {
26
- return {
27
- module: MikroOrmModule_1,
28
- imports: [mikro_orm_core_module_1.MikroOrmCoreModule.forRoot(options)],
29
- };
26
+ if (Array.isArray(options)) {
27
+ return options.map(o => mikro_orm_core_module_1.MikroOrmCoreModule.forRoot(o));
28
+ }
29
+ return mikro_orm_core_module_1.MikroOrmCoreModule.forRoot(options);
30
30
  }
31
31
  static forRootAsync(options) {
32
- return {
33
- module: MikroOrmModule_1,
34
- imports: [mikro_orm_core_module_1.MikroOrmCoreModule.forRootAsync(options)],
35
- };
32
+ if (Array.isArray(options)) {
33
+ return options.map(o => mikro_orm_core_module_1.MikroOrmCoreModule.forRootAsync(o));
34
+ }
35
+ return mikro_orm_core_module_1.MikroOrmCoreModule.forRootAsync(options);
36
36
  }
37
37
  static forFeature(options, contextName) {
38
38
  const entities = Array.isArray(options) ? options : (options.entities || []);
@@ -50,10 +50,7 @@ let MikroOrmModule = MikroOrmModule_1 = class MikroOrmModule {
50
50
  };
51
51
  }
52
52
  static forMiddleware(options) {
53
- return {
54
- module: MikroOrmModule_1,
55
- imports: [mikro_orm_middleware_module_1.MikroOrmMiddlewareModule.forMiddleware(options)],
56
- };
53
+ return mikro_orm_middleware_module_1.MikroOrmMiddlewareModule.forRoot(options);
57
54
  }
58
55
  };
59
56
  exports.MikroOrmModule = MikroOrmModule;
@@ -1,8 +1,8 @@
1
- import { EntityManager, type AnyEntity } from '@mikro-orm/core';
1
+ import { EntityManager, type AnyEntity, type ForkOptions } from '@mikro-orm/core';
2
2
  import { Scope, type Provider, type Type } from '@nestjs/common';
3
3
  import type { EntityName, MikroOrmModuleAsyncOptions } from './typings';
4
4
  export declare function createMikroOrmProvider(contextName?: string, type?: Type): Provider;
5
- export declare function createEntityManagerProvider(scope?: Scope, entityManager?: Type, contextName?: string): Provider<EntityManager>;
5
+ export declare function createEntityManagerProvider(scope?: Scope, entityManager?: Type, contextName?: string, forkOptions?: ForkOptions): Provider<EntityManager>;
6
6
  export declare function createMikroOrmAsyncOptionsProvider(options: MikroOrmModuleAsyncOptions): Provider;
7
7
  export declare function createAsyncProviders(options: MikroOrmModuleAsyncOptions): Provider[];
8
8
  export declare function createMikroOrmRepositoryProviders(entities: EntityName<AnyEntity>[], contextName?: string): Provider[];
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createMikroOrmRepositoryProviders = exports.createAsyncProviders = exports.createMikroOrmAsyncOptionsProvider = exports.createEntityManagerProvider = exports.createMikroOrmProvider = void 0;
3
+ exports.createMikroOrmProvider = createMikroOrmProvider;
4
+ exports.createEntityManagerProvider = createEntityManagerProvider;
5
+ exports.createMikroOrmAsyncOptionsProvider = createMikroOrmAsyncOptionsProvider;
6
+ exports.createAsyncProviders = createAsyncProviders;
7
+ exports.createMikroOrmRepositoryProviders = createMikroOrmRepositoryProviders;
4
8
  const core_1 = require("@mikro-orm/core");
5
9
  const mikro_orm_common_1 = require("./mikro-orm.common");
6
10
  const common_1 = require("@nestjs/common");
@@ -25,15 +29,14 @@ function createMikroOrmProvider(contextName, type = core_1.MikroORM) {
25
29
  if (!options || Object.keys(options).length === 0) {
26
30
  const config = await core_1.ConfigurationLoader.getConfiguration();
27
31
  config.set('logger', mikro_orm_common_1.logger.log.bind(mikro_orm_common_1.logger));
28
- options = config;
32
+ options = config.getAll();
29
33
  }
30
34
  return core_1.MikroORM.init(options);
31
35
  },
32
36
  inject: [mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS],
33
37
  };
34
38
  }
35
- exports.createMikroOrmProvider = createMikroOrmProvider;
36
- function createEntityManagerProvider(scope = common_1.Scope.DEFAULT, entityManager = core_1.EntityManager, contextName) {
39
+ function createEntityManagerProvider(scope = common_1.Scope.DEFAULT, entityManager = core_1.EntityManager, contextName, forkOptions) {
37
40
  if (!contextName && entityManager !== core_1.EntityManager) {
38
41
  return {
39
42
  provide: entityManager,
@@ -45,11 +48,10 @@ function createEntityManagerProvider(scope = common_1.Scope.DEFAULT, entityManag
45
48
  return {
46
49
  provide: contextName ? (0, mikro_orm_common_1.getEntityManagerToken)(contextName) : entityManager,
47
50
  scope,
48
- useFactory: (orm) => scope === common_1.Scope.DEFAULT ? orm.em : orm.em.fork(),
51
+ useFactory: (orm) => scope === common_1.Scope.DEFAULT ? orm.em : orm.em.fork(forkOptions),
49
52
  inject: [contextName ? (0, mikro_orm_common_1.getMikroORMToken)(contextName) : core_1.MikroORM],
50
53
  };
51
54
  }
52
- exports.createEntityManagerProvider = createEntityManagerProvider;
53
55
  function createMikroOrmAsyncOptionsProvider(options) {
54
56
  if (options.useFactory) {
55
57
  return {
@@ -73,7 +75,6 @@ function createMikroOrmAsyncOptionsProvider(options) {
73
75
  inject,
74
76
  };
75
77
  }
76
- exports.createMikroOrmAsyncOptionsProvider = createMikroOrmAsyncOptionsProvider;
77
78
  function createAsyncProviders(options) {
78
79
  if (options.useExisting || options.useFactory) {
79
80
  return [createMikroOrmAsyncOptionsProvider(options)];
@@ -86,7 +87,6 @@ function createAsyncProviders(options) {
86
87
  }
87
88
  throw new Error('Invalid MikroORM async options: one of `useClass`, `useExisting` or `useFactory` should be defined.');
88
89
  }
89
- exports.createAsyncProviders = createAsyncProviders;
90
90
  function createMikroOrmRepositoryProviders(entities, contextName) {
91
91
  const metadata = Object.values(core_1.MetadataStorage.getMetadata());
92
92
  const providers = [];
@@ -109,4 +109,3 @@ function createMikroOrmRepositoryProviders(entities, contextName) {
109
109
  });
110
110
  return providers;
111
111
  }
112
- exports.createMikroOrmRepositoryProviders = createMikroOrmRepositoryProviders;
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.MultipleMikroOrmMiddleware = void 0;
16
16
  const core_1 = require("@mikro-orm/core");
17
17
  const common_1 = require("@nestjs/common");
18
+ const mikro_orm_common_1 = require("./mikro-orm.common");
18
19
  let MultipleMikroOrmMiddleware = class MultipleMikroOrmMiddleware {
19
20
  constructor(orm) {
20
21
  this.orm = orm;
@@ -26,6 +27,6 @@ let MultipleMikroOrmMiddleware = class MultipleMikroOrmMiddleware {
26
27
  exports.MultipleMikroOrmMiddleware = MultipleMikroOrmMiddleware;
27
28
  exports.MultipleMikroOrmMiddleware = MultipleMikroOrmMiddleware = __decorate([
28
29
  (0, common_1.Injectable)(),
29
- __param(0, (0, common_1.Inject)('MikroORMs')),
30
+ __param(0, (0, mikro_orm_common_1.InjectMikroORMs)()),
30
31
  __metadata("design:paramtypes", [Array])
31
32
  ], MultipleMikroOrmMiddleware);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/nestjs",
3
- "version": "6.0.2",
3
+ "version": "6.1.1",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "Martin Adamek",
@@ -40,32 +40,32 @@
40
40
  "lint": "eslint src/**/*.ts"
41
41
  },
42
42
  "peerDependencies": {
43
- "@mikro-orm/core": "^6.0.0 || ^6.0.0-dev.0",
44
- "@nestjs/common": "^10.0.0",
45
- "@nestjs/core": "^10.0.0"
43
+ "@mikro-orm/core": "^6.0.0 || ^6.0.0-dev.0 || ^7.0.0-dev.0",
44
+ "@nestjs/common": "^10.0.0 || ^11.0.5",
45
+ "@nestjs/core": "^10.0.0 || ^11.0.5"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@mikro-orm/core": "^6.2.7",
49
49
  "@mikro-orm/sqlite": "^6.2.7",
50
- "@nestjs/common": "^10.3.8",
51
- "@nestjs/core": "^10.3.8",
52
- "@nestjs/platform-express": "^10.3.8",
53
- "@nestjs/testing": "^10.3.8",
50
+ "@nestjs/common": "^11.0.5",
51
+ "@nestjs/core": "^11.0.5",
52
+ "@nestjs/platform-express": "^11.0.5",
53
+ "@nestjs/testing": "^11.0.5",
54
+ "@stylistic/eslint-plugin-ts": "^3.0.1",
54
55
  "@types/jest": "^29.5.12",
55
- "@types/node": "^20.12.12",
56
+ "@types/node": "^22.0.0",
56
57
  "@types/supertest": "^6.0.2",
57
- "@typescript-eslint/eslint-plugin": "~7.12.0",
58
- "@typescript-eslint/parser": "~7.12.0",
59
58
  "conventional-changelog": "^6.0.0",
60
59
  "conventional-changelog-cli": "^5.0.0",
61
- "eslint": "^8.57.0",
62
- "eslint-plugin-import": "^2.29.1",
60
+ "eslint": "^9.19.0",
61
+ "eslint-plugin-import": "^2.31.0",
63
62
  "jest": "^29.7.0",
64
63
  "rxjs": "^7.8.1",
65
64
  "supertest": "^7.0.0",
66
65
  "ts-jest": "^29.1.2",
67
66
  "ts-node": "^10.9.2",
68
- "typescript": "5.4.5"
67
+ "typescript": "5.7.3",
68
+ "typescript-eslint": "^8.22.0"
69
69
  },
70
70
  "commitlint": {
71
71
  "extends": [
@@ -105,5 +105,5 @@
105
105
  "engines": {
106
106
  "node": ">= 18.12.0"
107
107
  },
108
- "packageManager": "yarn@4.2.2"
108
+ "packageManager": "yarn@4.6.0"
109
109
  }
package/typings.d.ts CHANGED
@@ -1,11 +1,27 @@
1
- import type { AnyEntity, EntityName as CoreEntityName, EntitySchema, IDatabaseDriver, Options } from '@mikro-orm/core';
1
+ import type { AnyEntity, Constructor, EntityName as CoreEntityName, EntitySchema, ForkOptions, IDatabaseDriver, Options } from '@mikro-orm/core';
2
2
  import type { MiddlewareConsumer, ModuleMetadata, Scope, Type } from '@nestjs/common';
3
3
  import type { AbstractHttpAdapter } from '@nestjs/core';
4
+ export type MaybePromise<T> = T | Promise<T>;
4
5
  export interface NestMiddlewareConsumer extends MiddlewareConsumer {
5
6
  httpAdapter: AbstractHttpAdapter;
6
7
  }
7
8
  type MikroOrmNestScopeOptions = {
9
+ /**
10
+ * The NestJS provider scope to use for the EntityManager (and any subsequent downstream records).
11
+ *
12
+ * This scope will also impact the scope of Entity Repositories as they depend on the EntityManager.
13
+ *
14
+ * @see [NestJS Scope Hierarchy](https://docs.nestjs.com/fundamentals/injection-scopes#scope-hierarchy)
15
+ */
8
16
  scope?: Scope;
17
+ /**
18
+ * An optional configuration object to use when forking the Event Manager if it is configured with a scope other than Scope.DEFAULT
19
+ *
20
+ * This configuration option has no effect when the scope is set to Scope.DEFAULT.
21
+ *
22
+ * https://mikro-orm.io/api/core/interface/ForkOptions
23
+ */
24
+ forkOptions?: ForkOptions;
9
25
  };
10
26
  export type MikroOrmMiddlewareModuleOptions = {
11
27
  /**
@@ -19,10 +35,27 @@ export type MikroOrmMiddlewareModuleOptions = {
19
35
  };
20
36
  export type MikroOrmModuleOptions<D extends IDatabaseDriver = IDatabaseDriver> = {
21
37
  registerRequestContext?: boolean;
38
+ /**
39
+ * Specifies whether or not to automatically load the entities based on MikroOrmModule.forFeature invocations.
40
+ *
41
+ * @see [MikroOrm - NestJS - Load Entities Automatically](https://mikro-orm.io/docs/usage-with-nestjs#load-entities-automatically)
42
+ *
43
+ * @default false
44
+ */
22
45
  autoLoadEntities?: boolean;
23
46
  } & Options<D> & MikroOrmMiddlewareModuleOptions;
24
47
  export interface MikroOrmModuleFeatureOptions {
48
+ /**
49
+ * The entities to provide an EntityRepository for.
50
+ *
51
+ * @see [MikroOrm - NestJS - Repositories](https://mikro-orm.io/docs/usage-with-nestjs#repositories)
52
+ */
25
53
  entities?: EntityName<AnyEntity>[];
54
+ /**
55
+ * The context (database connection) to use for the entity repository.
56
+ *
57
+ * @see [MikroOrm - NestJS - Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
58
+ */
26
59
  contextName?: string;
27
60
  }
28
61
  export interface MikroOrmOptionsFactory<D extends IDatabaseDriver = IDatabaseDriver> {
@@ -31,10 +64,18 @@ export interface MikroOrmOptionsFactory<D extends IDatabaseDriver = IDatabaseDri
31
64
  export interface MikroOrmModuleSyncOptions extends MikroOrmModuleOptions, MikroOrmNestScopeOptions {
32
65
  }
33
66
  export interface MikroOrmModuleAsyncOptions<D extends IDatabaseDriver = IDatabaseDriver> extends Pick<ModuleMetadata, 'imports' | 'providers'>, MikroOrmNestScopeOptions {
67
+ /**
68
+ * The context name (database connection) to specify for this instance.
69
+ *
70
+ * When injecting repositories or entity manager instances, this context name will need to be specified where there are multiple datbaase connections.
71
+ *
72
+ * @see [MikroOrm - NestJS - Multiple Database Connections](https://mikro-orm.io/docs/usage-with-nestjs#multiple-database-connections)
73
+ */
34
74
  contextName?: string;
35
75
  useExisting?: Type<MikroOrmOptionsFactory<D>>;
36
76
  useClass?: Type<MikroOrmOptionsFactory<D>>;
37
77
  useFactory?: (...args: any[]) => Promise<Omit<MikroOrmModuleOptions<D>, 'contextName'>> | Omit<MikroOrmModuleOptions<D>, 'contextName'>;
78
+ driver?: Constructor<D>;
38
79
  inject?: any[];
39
80
  }
40
81
  export declare type EntityName<T extends AnyEntity<T>> = CoreEntityName<T> | EntitySchema;