@mikro-orm/nestjs 4.3.0 → 5.0.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
@@ -178,6 +178,8 @@ export class MyService {
178
178
 
179
179
  ## Using `AsyncLocalStorage` for request context
180
180
 
181
+ > Since v5 AsyncLocalStorage is used inside RequestContext helper so this section is no longer valid.
182
+
181
183
  By default, the `domain` api is used in the `RequestContext` helper. Since `@mikro-orm/core@4.0.3`,
182
184
  you can use the new `AsyncLocalStorage` too, if you are on up to date node version:
183
185
 
@@ -208,8 +210,7 @@ app.use((req, res, next) => {
208
210
 
209
211
  ## Using NestJS `Injection Scopes` for request context
210
212
 
211
- By default, the `domain` api is used in the `RequestContext` helper. Since `@nestjs/common@6`,
212
- you can use the new `Injection Scopes` (https://docs.nestjs.com/fundamentals/injection-scopes) too:
213
+ Since `@nestjs/common@6`, you can use the new `Injection Scopes` (https://docs.nestjs.com/fundamentals/injection-scopes) too:
213
214
 
214
215
  ```typescript
215
216
  import { Scope } from '@nestjs/common';
@@ -268,7 +269,7 @@ the Nest.js DI container.
268
269
  `**./author.entity.ts**`
269
270
 
270
271
  ```ts
271
- @Entity()
272
+ @Entity({ customRepository: () => AuthorRepository })
272
273
  export class Author {
273
274
 
274
275
  // to allow inference in `em.getRepository()`
@@ -280,7 +281,6 @@ export class Author {
280
281
  `**./author.repository.ts**`
281
282
 
282
283
  ```ts
283
- @Repository(Author)
284
284
  export class AuthorRepository extends EntityRepository<Author> {
285
285
 
286
286
  // your custom methods...
@@ -300,6 +300,90 @@ export class MyService {
300
300
  }
301
301
  ```
302
302
 
303
+ ## App shutdown and cleanup
304
+
305
+ By default, NestJS does not listen for system process termination signals (for example SIGTERM). Because of this, the MikroORM shutdown logic will never executed if the process is terminated, which could lead to database connections remaining open and consuming resources. To enable this, the `enableShutdownHooks` function needs to be called when starting up the application.
306
+
307
+ ```ts
308
+ async function bootstrap() {
309
+ const app = await NestFactory.create(AppModule);
310
+
311
+ // Starts listening for shutdown hooks
312
+ app.enableShutdownHooks();
313
+
314
+ await app.listen(3000);
315
+ }
316
+ ```
317
+
318
+ More information about [enableShutdownHooks](https://docs.nestjs.com/fundamentals/lifecycle-events#application-shutdown)
319
+
320
+ ## Multiple Database Connections
321
+
322
+ 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`
323
+
324
+ ```typescript
325
+ @Module({
326
+ imports: [
327
+ MikroOrmModule.forRoot({
328
+ contextName: 'db1',
329
+ registerRequestContext: false, // disable automatatic middleware
330
+ ...
331
+ }),
332
+ MikroOrmModule.forRoot({
333
+ contextName: 'db2',
334
+ registerRequestContext: false, // disable automatatic middleware
335
+ ...
336
+ }),
337
+ MikroOrmModule.forMiddleware()
338
+ ],
339
+ controllers: [AppController],
340
+ providers: [AppService],
341
+ })
342
+ export class AppModule {}
343
+ ```
344
+
345
+ 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:
346
+
347
+ ```ts
348
+ @Injectable()
349
+ export class MyService {
350
+
351
+ constructor(@InjectMikroORM('db1') private readonly orm1: MikroORM,
352
+ @InjectMikroORM('db2') private readonly orm2: MikroORM,
353
+ @InjectEntityManager('db1') private readonly em1: EntityManager,
354
+ @InjectEntityManager('db2') private readonly em2: EntityManager) { }
355
+
356
+ }
357
+ ```
358
+
359
+ When defining your repositories with `forFeature()` method you will need to set which `contextName` you want it registered against:
360
+
361
+ ```typescript
362
+ // photo.module.ts
363
+
364
+ @Module({
365
+ imports: [MikroOrmModule.forFeature([Photo], 'db1')],
366
+ providers: [PhotoService],
367
+ controllers: [PhotoController],
368
+ })
369
+ export class PhotoModule {}
370
+ ```
371
+
372
+ When using the `@InjectRepository` decorator you will also need to pass the `contextName` you want to get it from:
373
+
374
+ ```typescript
375
+ @Injectable()
376
+ export class PhotoService {
377
+ constructor(
378
+ @InjectRepository(Photo, 'db1')
379
+ private readonly photoRepository: EntityRepository<Photo>
380
+ ) {}
381
+
382
+ // ...
383
+
384
+ }
385
+ ```
386
+
303
387
  ## Testing
304
388
 
305
389
  The `nestjs-mikro-orm` package exposes `getRepositoryToken()` function that returns prepared token based on a given entity to allow mocking the repository.
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './mikro-orm.module';
2
2
  export * from './mikro-orm.common';
3
3
  export * from './mikro-orm.middleware';
4
+ export * from './multiple-mikro-orm.middleware';
4
5
  export * from './typings';
package/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -13,4 +17,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
17
  __exportStar(require("./mikro-orm.module"), exports);
14
18
  __exportStar(require("./mikro-orm.common"), exports);
15
19
  __exportStar(require("./mikro-orm.middleware"), exports);
20
+ __exportStar(require("./multiple-mikro-orm.middleware"), exports);
16
21
  __exportStar(require("./typings"), exports);
@@ -0,0 +1,3 @@
1
+ import type { MikroOrmMiddlewareModuleOptions } from './typings';
2
+ import type { MiddlewareConsumer } from '@nestjs/common';
3
+ export declare function forRoutesPath(options: MikroOrmMiddlewareModuleOptions, consumer: MiddlewareConsumer): string;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.forRoutesPath = void 0;
4
+ function forRoutesPath(options, consumer) {
5
+ const isNestMiddleware = (consumer) => {
6
+ return typeof consumer.httpAdapter === 'object';
7
+ };
8
+ const usingFastify = (consumer) => {
9
+ return consumer.httpAdapter.constructor.name.toLowerCase().startsWith('fastify');
10
+ };
11
+ return options.forRoutesPath ??
12
+ (isNestMiddleware(consumer) && usingFastify(consumer) ? '(.*)' : '*');
13
+ }
14
+ exports.forRoutesPath = forRoutesPath;
@@ -1,6 +1,7 @@
1
- import { DynamicModule, MiddlewareConsumer, OnApplicationShutdown } from '@nestjs/common';
1
+ import type { DynamicModule, MiddlewareConsumer, OnApplicationShutdown } from '@nestjs/common';
2
2
  import { ModuleRef } from '@nestjs/core';
3
- import { MikroOrmModuleAsyncOptions, MikroOrmModuleOptions, MikroOrmModuleSyncOptions } from './typings';
3
+ import type { MikroOrmModuleAsyncOptions, MikroOrmModuleSyncOptions } from './typings';
4
+ import { MikroOrmModuleOptions } from './typings';
4
5
  export declare class MikroOrmCoreModule implements OnApplicationShutdown {
5
6
  private readonly options;
6
7
  private readonly moduleRef;
@@ -9,4 +10,5 @@ export declare class MikroOrmCoreModule implements OnApplicationShutdown {
9
10
  static forRootAsync(options: MikroOrmModuleAsyncOptions): Promise<DynamicModule>;
10
11
  onApplicationShutdown(): Promise<void>;
11
12
  configure(consumer: MiddlewareConsumer): void;
13
+ private static setContextName;
12
14
  }
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -37,22 +41,15 @@ const core_1 = require("@mikro-orm/core");
37
41
  const common_1 = require("@nestjs/common");
38
42
  const core_2 = require("@nestjs/core");
39
43
  const mikro_orm_common_1 = require("./mikro-orm.common");
40
- const mikro_orm_middleware_1 = require("./mikro-orm.middleware");
41
44
  const mikro_orm_providers_1 = require("./mikro-orm.providers");
42
- var EntityManagerModuleName;
43
- (function (EntityManagerModuleName) {
44
- EntityManagerModuleName["Knex"] = "@mikro-orm/knex";
45
- EntityManagerModuleName["MongoDb"] = "@mikro-orm/mongodb";
46
- })(EntityManagerModuleName || (EntityManagerModuleName = {}));
47
- async function whenModuleAvailable(moduleName, returnFn) {
45
+ const mikro_orm_middleware_1 = require("./mikro-orm.middleware");
46
+ const middleware_helper_1 = require("./middleware.helper");
47
+ async function tryRequire(cb) {
48
48
  try {
49
- const module = await Promise.resolve().then(() => __importStar(require(moduleName)));
50
- // TReturnValue may be incorrect if expecting it to extend Promise<T> since its being awaited in the return
51
- // casting to Awaited<TReturnValue> to satisfy the return type will prevent that confusion
52
- return [await returnFn(module)];
49
+ return await cb();
53
50
  }
54
- catch (err) {
55
- return [];
51
+ catch {
52
+ return undefined; // ignore, optional dependency
56
53
  }
57
54
  }
58
55
  let MikroOrmCoreModule = MikroOrmCoreModule_1 = class MikroOrmCoreModule {
@@ -61,70 +58,80 @@ let MikroOrmCoreModule = MikroOrmCoreModule_1 = class MikroOrmCoreModule {
61
58
  this.moduleRef = moduleRef;
62
59
  }
63
60
  static async forRoot(options) {
61
+ const contextName = this.setContextName(options?.contextName);
62
+ const knex = await tryRequire(() => Promise.resolve().then(() => __importStar(require('@mikro-orm/knex'))));
63
+ const mongo = await tryRequire(() => Promise.resolve().then(() => __importStar(require('@mikro-orm/mongodb'))));
64
64
  return {
65
65
  module: MikroOrmCoreModule_1,
66
66
  providers: [
67
67
  { provide: mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS, useValue: options || {} },
68
- mikro_orm_providers_1.createMikroOrmProvider(),
69
- mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options === null || options === void 0 ? void 0 : options.scope),
70
- ...(await whenModuleAvailable(EntityManagerModuleName.Knex, ({ SqlEntityManager }) => mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options === null || options === void 0 ? void 0 : options.scope, SqlEntityManager))),
71
- ...(await whenModuleAvailable(EntityManagerModuleName.MongoDb, ({ MongoEntityManager }) => mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options === null || options === void 0 ? void 0 : options.scope, MongoEntityManager))),
68
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName),
69
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, core_1.EntityManager, contextName),
70
+ ...(knex ? [(0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, knex.SqlEntityManager, contextName)] : []),
71
+ ...(mongo ? [(0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, mongo.MongoEntityManager, contextName)] : []),
72
72
  ],
73
73
  exports: [
74
- core_1.MikroORM,
75
- core_1.EntityManager,
76
- ...(await whenModuleAvailable(EntityManagerModuleName.Knex, ({ SqlEntityManager }) => SqlEntityManager)),
77
- ...(await whenModuleAvailable(EntityManagerModuleName.MongoDb, ({ MongoEntityManager }) => MongoEntityManager)),
74
+ contextName ? (0, mikro_orm_common_1.getMikroORMToken)(contextName) : core_1.MikroORM,
75
+ contextName ? (0, mikro_orm_common_1.getEntityManagerToken)(contextName) : core_1.EntityManager,
76
+ ...(knex ? (contextName ? [] : [knex.SqlEntityManager]) : []),
77
+ ...(mongo ? (contextName ? [] : [mongo.MongoEntityManager]) : []),
78
78
  ],
79
79
  };
80
80
  }
81
81
  static async forRootAsync(options) {
82
+ const contextName = this.setContextName(options?.contextName);
83
+ const knex = await tryRequire(() => Promise.resolve().then(() => __importStar(require('@mikro-orm/knex'))));
84
+ const mongo = await tryRequire(() => Promise.resolve().then(() => __importStar(require('@mikro-orm/mongodb'))));
82
85
  return {
83
86
  module: MikroOrmCoreModule_1,
84
87
  imports: options.imports || [],
85
88
  providers: [
86
89
  ...(options.providers || []),
87
- ...mikro_orm_providers_1.createAsyncProviders(options),
88
- mikro_orm_providers_1.createMikroOrmProvider(),
89
- mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options.scope),
90
- ...(await whenModuleAvailable(EntityManagerModuleName.Knex, ({ SqlEntityManager }) => mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options.scope, SqlEntityManager))),
91
- ...(await whenModuleAvailable(EntityManagerModuleName.MongoDb, ({ MongoEntityManager }) => mikro_orm_providers_1.createMikroOrmEntityManagerProvider(options.scope, MongoEntityManager))),
90
+ ...(0, mikro_orm_providers_1.createAsyncProviders)({ ...options, contextName: options.contextName }),
91
+ (0, mikro_orm_providers_1.createMikroOrmProvider)(contextName),
92
+ (0, mikro_orm_providers_1.createEntityManagerProvider)(options.scope, core_1.EntityManager, contextName),
93
+ ...(knex ? [(0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, knex.SqlEntityManager, contextName)] : []),
94
+ ...(mongo ? [(0, mikro_orm_providers_1.createEntityManagerProvider)(options?.scope, mongo.MongoEntityManager, contextName)] : []),
92
95
  ],
93
96
  exports: [
94
- core_1.MikroORM,
95
- core_1.EntityManager,
96
- ...(await whenModuleAvailable(EntityManagerModuleName.Knex, ({ SqlEntityManager }) => SqlEntityManager)),
97
- ...(await whenModuleAvailable(EntityManagerModuleName.MongoDb, ({ MongoEntityManager }) => MongoEntityManager)),
97
+ contextName ? (0, mikro_orm_common_1.getMikroORMToken)(contextName) : core_1.MikroORM,
98
+ contextName ? (0, mikro_orm_common_1.getEntityManagerToken)(contextName) : core_1.EntityManager,
99
+ ...(knex ? (contextName ? [] : [knex.SqlEntityManager]) : []),
100
+ ...(mongo ? (contextName ? [] : [mongo.MongoEntityManager]) : []),
98
101
  ],
99
102
  };
100
103
  }
101
104
  async onApplicationShutdown() {
102
- const orm = this.moduleRef.get(core_1.MikroORM);
105
+ const token = this.options.contextName ? (0, mikro_orm_common_1.getMikroORMToken)(this.options.contextName) : core_1.MikroORM;
106
+ const orm = this.moduleRef.get(token);
103
107
  if (orm) {
104
108
  await orm.close();
105
109
  }
110
+ mikro_orm_common_1.CONTEXT_NAMES.length = 0;
106
111
  }
107
112
  configure(consumer) {
108
- var _a;
109
113
  if (this.options.registerRequestContext === false) {
110
114
  return;
111
115
  }
112
- const isNestMiddleware = (consumer) => {
113
- return typeof consumer.httpAdapter === 'object';
114
- };
115
- const usingFastify = (consumer) => {
116
- return consumer.httpAdapter.constructor.name.toLowerCase().startsWith('fastify');
117
- };
118
- const forRoutesPath = (_a = this.options.forRoutesPath) !== null && _a !== void 0 ? _a : (isNestMiddleware(consumer) && usingFastify(consumer) ? '(.*)' : '*');
119
116
  consumer
120
117
  .apply(mikro_orm_middleware_1.MikroOrmMiddleware) // register request context automatically
121
- .forRoutes({ path: forRoutesPath, method: common_1.RequestMethod.ALL });
118
+ .forRoutes({ path: (0, middleware_helper_1.forRoutesPath)(this.options, consumer), method: common_1.RequestMethod.ALL });
119
+ }
120
+ static setContextName(contextName) {
121
+ if (!contextName) {
122
+ return;
123
+ }
124
+ if (mikro_orm_common_1.CONTEXT_NAMES.includes(contextName)) {
125
+ throw new Error(`ContextName '${contextName}' already registered`);
126
+ }
127
+ mikro_orm_common_1.CONTEXT_NAMES.push(contextName);
128
+ return contextName;
122
129
  }
123
130
  };
124
131
  MikroOrmCoreModule = MikroOrmCoreModule_1 = __decorate([
125
- common_1.Global(),
126
- common_1.Module({}),
127
- __param(0, common_1.Inject(mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS)),
132
+ (0, common_1.Global)(),
133
+ (0, common_1.Module)({}),
134
+ __param(0, (0, common_1.Inject)(mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS)),
128
135
  __metadata("design:paramtypes", [Object, core_2.ModuleRef])
129
136
  ], MikroOrmCoreModule);
130
137
  exports.MikroOrmCoreModule = MikroOrmCoreModule;
@@ -0,0 +1,22 @@
1
+ import type { MiddlewareConsumer } from '@nestjs/common';
2
+ import { MikroOrmMiddlewareModuleOptions } from './typings';
3
+ import type { MikroORM } from '@mikro-orm/core';
4
+ export declare class MikroOrmMiddlewareModule {
5
+ private readonly options;
6
+ constructor(options: MikroOrmMiddlewareModuleOptions);
7
+ static forMiddleware(options?: MikroOrmMiddlewareModuleOptions): {
8
+ module: typeof MikroOrmMiddlewareModule;
9
+ providers: ({
10
+ provide: symbol;
11
+ useValue: MikroOrmMiddlewareModuleOptions;
12
+ useFactory?: undefined;
13
+ inject?: undefined;
14
+ } | {
15
+ provide: string;
16
+ useFactory: (...args: MikroORM[]) => MikroORM<import("@mikro-orm/core").IDatabaseDriver<import("@mikro-orm/core").Connection>>[];
17
+ inject: string[];
18
+ useValue?: undefined;
19
+ })[];
20
+ };
21
+ configure(consumer: MiddlewareConsumer): void;
22
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var MikroOrmMiddlewareModule_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.MikroOrmMiddlewareModule = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const mikro_orm_common_1 = require("./mikro-orm.common");
19
+ const multiple_mikro_orm_middleware_1 = require("./multiple-mikro-orm.middleware");
20
+ const middleware_helper_1 = require("./middleware.helper");
21
+ let MikroOrmMiddlewareModule = MikroOrmMiddlewareModule_1 = class MikroOrmMiddlewareModule {
22
+ constructor(options) {
23
+ this.options = options;
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
29
+ const inject = mikro_orm_common_1.CONTEXT_NAMES.map(name => (0, mikro_orm_common_1.getMikroORMToken)(name));
30
+ return {
31
+ module: MikroOrmMiddlewareModule_1,
32
+ providers: [
33
+ { provide: mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS, useValue: options || {} },
34
+ {
35
+ provide: 'MikroORMs',
36
+ useFactory: (...args) => args,
37
+ inject,
38
+ },
39
+ ],
40
+ };
41
+ }
42
+ configure(consumer) {
43
+ consumer
44
+ .apply(multiple_mikro_orm_middleware_1.MultipleMikroOrmMiddleware)
45
+ .forRoutes({ path: (0, middleware_helper_1.forRoutesPath)(this.options, consumer), method: common_1.RequestMethod.ALL });
46
+ }
47
+ };
48
+ MikroOrmMiddlewareModule = MikroOrmMiddlewareModule_1 = __decorate([
49
+ (0, common_1.Global)(),
50
+ (0, common_1.Module)({}),
51
+ __param(0, (0, common_1.Inject)(mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS)),
52
+ __metadata("design:paramtypes", [Object])
53
+ ], MikroOrmMiddlewareModule);
54
+ exports.MikroOrmMiddlewareModule = MikroOrmMiddlewareModule;
@@ -1,8 +1,11 @@
1
- import { AnyEntity, EntityName } from '@mikro-orm/core';
1
+ import type { EntityName } from '@mikro-orm/core';
2
2
  import { Logger } from '@nestjs/common';
3
3
  export declare const MIKRO_ORM_MODULE_OPTIONS: unique symbol;
4
- export declare const REGISTERED_ENTITIES: Set<EntityName<AnyEntity<any>>>;
4
+ export declare const CONTEXT_NAMES: string[];
5
5
  export declare const logger: Logger;
6
- export declare const getRepositoryToken: <T>(entity: EntityName<T>) => string;
7
- export declare const InjectRepository: <T>(entity: EntityName<T>) => (target: object, key: string | symbol, index?: number | undefined) => void;
8
- export declare function UseRequestContext(): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
6
+ export declare const getMikroORMToken: (name: string) => string;
7
+ export declare const InjectMikroORM: (name: string) => (target: object, key: string | symbol, index?: number | undefined) => void;
8
+ export declare const getEntityManagerToken: (name: string) => string;
9
+ export declare const InjectEntityManager: (name: string) => (target: object, key: string | symbol, index?: number | undefined) => void;
10
+ export declare const getRepositoryToken: <T>(entity: EntityName<T>, name?: string | undefined) => string;
11
+ export declare const InjectRepository: <T>(entity: EntityName<T>, name?: string | undefined) => (target: object, key: string | symbol, index?: number | undefined) => void;
@@ -1,29 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UseRequestContext = exports.InjectRepository = exports.getRepositoryToken = exports.logger = exports.REGISTERED_ENTITIES = exports.MIKRO_ORM_MODULE_OPTIONS = void 0;
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;
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
- exports.REGISTERED_ENTITIES = new Set();
7
+ exports.CONTEXT_NAMES = [];
8
8
  exports.logger = new common_1.Logger(core_1.MikroORM.name);
9
- const getRepositoryToken = (entity) => `${core_1.Utils.className(entity)}Repository`;
9
+ const getMikroORMToken = (name) => `${name}_MikroORM`;
10
+ exports.getMikroORMToken = getMikroORMToken;
11
+ const InjectMikroORM = (name) => (0, common_1.Inject)((0, exports.getMikroORMToken)(name));
12
+ exports.InjectMikroORM = InjectMikroORM;
13
+ const getEntityManagerToken = (name) => `${name}_EntityManager`;
14
+ exports.getEntityManagerToken = getEntityManagerToken;
15
+ const InjectEntityManager = (name) => (0, common_1.Inject)((0, exports.getEntityManagerToken)(name));
16
+ exports.InjectEntityManager = InjectEntityManager;
17
+ const getRepositoryToken = (entity, name) => {
18
+ const suffix = name ? `_${name}` : '';
19
+ return `${core_1.Utils.className(entity)}Repository${suffix}`;
20
+ };
10
21
  exports.getRepositoryToken = getRepositoryToken;
11
- const InjectRepository = (entity) => common_1.Inject(exports.getRepositoryToken(entity));
22
+ const InjectRepository = (entity, name) => (0, common_1.Inject)((0, exports.getRepositoryToken)(entity, name));
12
23
  exports.InjectRepository = InjectRepository;
13
- function UseRequestContext() {
14
- return function (target, propertyKey, descriptor) {
15
- const originalMethod = descriptor.value;
16
- descriptor.value = async function (...args) {
17
- // eslint-disable-next-line @typescript-eslint/no-this-alias
18
- const context = this;
19
- if (!(context.orm instanceof core_1.MikroORM)) {
20
- throw new Error('@UseRequestContext() decorator can only be applied to methods of classes that carry `orm: MikroORM`');
21
- }
22
- await core_1.RequestContext.createAsync(context.orm.em, async () => {
23
- await originalMethod.apply(context, args);
24
- });
25
- };
26
- return descriptor;
27
- };
28
- }
29
- exports.UseRequestContext = UseRequestContext;
@@ -0,0 +1,7 @@
1
+ import type { AnyEntity, EntityName } from '@mikro-orm/core';
2
+ export declare class MikroOrmEntitiesStorage {
3
+ private static readonly storage;
4
+ static addEntity(entity: EntityName<AnyEntity>, contextName?: string): void;
5
+ static getEntities(contextName?: string): never[] | IterableIterator<EntityName<AnyEntity<any>>>;
6
+ static clear(contextName?: string): void;
7
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MikroOrmEntitiesStorage = void 0;
4
+ class MikroOrmEntitiesStorage {
5
+ static addEntity(entity, contextName = 'default') {
6
+ let set = this.storage.get(contextName);
7
+ if (!set) {
8
+ set = new Set();
9
+ this.storage.set(contextName, set);
10
+ }
11
+ set.add(entity);
12
+ }
13
+ static getEntities(contextName = 'default') {
14
+ return this.storage.get(contextName)?.values() || [];
15
+ }
16
+ static clear(contextName = 'default') {
17
+ const set = this.storage.get(contextName);
18
+ if (!set) {
19
+ return;
20
+ }
21
+ set.clear();
22
+ }
23
+ }
24
+ exports.MikroOrmEntitiesStorage = MikroOrmEntitiesStorage;
25
+ MikroOrmEntitiesStorage.storage = new Map();
@@ -1,5 +1,5 @@
1
1
  import { MikroORM } from '@mikro-orm/core';
2
- import { NestMiddleware } from '@nestjs/common';
2
+ import type { NestMiddleware } from '@nestjs/common';
3
3
  export declare class MikroOrmMiddleware implements NestMiddleware {
4
4
  private readonly orm;
5
5
  constructor(orm: MikroORM);
@@ -21,7 +21,7 @@ let MikroOrmMiddleware = class MikroOrmMiddleware {
21
21
  }
22
22
  };
23
23
  MikroOrmMiddleware = __decorate([
24
- common_1.Injectable(),
24
+ (0, common_1.Injectable)(),
25
25
  __metadata("design:paramtypes", [core_1.MikroORM])
26
26
  ], MikroOrmMiddleware);
27
27
  exports.MikroOrmMiddleware = MikroOrmMiddleware;
@@ -1,10 +1,9 @@
1
- import { AnyEntity, EntityName } from '@mikro-orm/core';
2
- import { DynamicModule } from '@nestjs/common';
3
- import { MikroOrmModuleAsyncOptions, MikroOrmModuleSyncOptions } from './typings';
1
+ import type { AnyEntity, EntityName } from '@mikro-orm/core';
2
+ import type { DynamicModule } from '@nestjs/common';
3
+ import type { MikroOrmModuleAsyncOptions, MikroOrmModuleSyncOptions, MikroOrmMiddlewareModuleOptions, MikroOrmModuleFeatureOptions } from './typings';
4
4
  export declare class MikroOrmModule {
5
5
  static forRoot(options?: MikroOrmModuleSyncOptions): DynamicModule;
6
6
  static forRootAsync(options: MikroOrmModuleAsyncOptions): DynamicModule;
7
- static forFeature(options: EntityName<AnyEntity>[] | {
8
- entities?: EntityName<AnyEntity>[];
9
- }): DynamicModule;
7
+ static forFeature(options: EntityName<AnyEntity>[] | MikroOrmModuleFeatureOptions, contextName?: string): DynamicModule;
8
+ static forMiddleware(options?: MikroOrmMiddlewareModuleOptions): DynamicModule;
10
9
  }
@@ -12,7 +12,8 @@ const core_1 = require("@mikro-orm/core");
12
12
  const common_1 = require("@nestjs/common");
13
13
  const mikro_orm_providers_1 = require("./mikro-orm.providers");
14
14
  const mikro_orm_core_module_1 = require("./mikro-orm-core.module");
15
- const mikro_orm_common_1 = require("./mikro-orm.common");
15
+ const mikro_orm_middleware_module_1 = require("./mikro-orm-middleware.module");
16
+ const mikro_orm_entities_storage_1 = require("./mikro-orm.entities.storage");
16
17
  let MikroOrmModule = MikroOrmModule_1 = class MikroOrmModule {
17
18
  static forRoot(options) {
18
19
  return {
@@ -26,12 +27,13 @@ let MikroOrmModule = MikroOrmModule_1 = class MikroOrmModule {
26
27
  imports: [mikro_orm_core_module_1.MikroOrmCoreModule.forRootAsync(options)],
27
28
  };
28
29
  }
29
- static forFeature(options) {
30
+ static forFeature(options, contextName) {
30
31
  const entities = Array.isArray(options) ? options : (options.entities || []);
31
- const providers = mikro_orm_providers_1.createMikroOrmRepositoryProviders(entities);
32
+ const name = (Array.isArray(options) || contextName) ? contextName : options.contextName;
33
+ const providers = (0, mikro_orm_providers_1.createMikroOrmRepositoryProviders)(entities, name);
32
34
  for (const e of entities) {
33
35
  if (!core_1.Utils.isString(e)) {
34
- mikro_orm_common_1.REGISTERED_ENTITIES.add(e);
36
+ mikro_orm_entities_storage_1.MikroOrmEntitiesStorage.addEntity(e, name);
35
37
  }
36
38
  }
37
39
  return {
@@ -40,8 +42,14 @@ let MikroOrmModule = MikroOrmModule_1 = class MikroOrmModule {
40
42
  exports: [...providers],
41
43
  };
42
44
  }
45
+ static forMiddleware(options) {
46
+ return {
47
+ module: MikroOrmModule_1,
48
+ imports: [mikro_orm_middleware_module_1.MikroOrmMiddlewareModule.forMiddleware(options)],
49
+ };
50
+ }
43
51
  };
44
52
  MikroOrmModule = MikroOrmModule_1 = __decorate([
45
- common_1.Module({})
53
+ (0, common_1.Module)({})
46
54
  ], MikroOrmModule);
47
55
  exports.MikroOrmModule = MikroOrmModule;
@@ -1,9 +1,10 @@
1
- import { AnyEntity, EntityManager, EntityName, EntityManagerType, IDatabaseDriver } from '@mikro-orm/core';
2
- import { MikroOrmModuleAsyncOptions } from './typings';
3
- import { Provider, Scope, Type } from '@nestjs/common';
4
- export declare const createMikroOrmProvider: () => Provider;
5
- export declare type EntityManagerProvider = Provider<IDatabaseDriver[typeof EntityManagerType] & EntityManager>;
6
- export declare const createMikroOrmEntityManagerProvider: (scope?: Scope, entityManager?: Type<EntityManager>) => EntityManagerProvider;
7
- export declare const createMikroOrmAsyncOptionsProvider: (options: MikroOrmModuleAsyncOptions) => Provider;
8
- export declare const createAsyncProviders: (options: MikroOrmModuleAsyncOptions) => Provider[];
9
- export declare const createMikroOrmRepositoryProviders: (entities: EntityName<AnyEntity>[]) => Provider[];
1
+ import type { AnyEntity, EntityName } from '@mikro-orm/core';
2
+ import { EntityManager } from '@mikro-orm/core';
3
+ import type { MikroOrmModuleAsyncOptions } from './typings';
4
+ import type { Provider, Type } from '@nestjs/common';
5
+ import { Scope } from '@nestjs/common';
6
+ export declare function createMikroOrmProvider(contextName?: string): Provider;
7
+ export declare function createEntityManagerProvider(scope?: Scope, entityManager?: Type, contextName?: string): Provider<EntityManager>;
8
+ export declare function createMikroOrmAsyncOptionsProvider(options: MikroOrmModuleAsyncOptions): Provider;
9
+ export declare function createAsyncProviders(options: MikroOrmModuleAsyncOptions): Provider[];
10
+ export declare function createMikroOrmRepositoryProviders(entities: EntityName<AnyEntity>[], contextName?: string): Provider[];
@@ -1,37 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createMikroOrmRepositoryProviders = exports.createAsyncProviders = exports.createMikroOrmAsyncOptionsProvider = exports.createMikroOrmEntityManagerProvider = exports.createMikroOrmProvider = void 0;
3
+ exports.createMikroOrmRepositoryProviders = exports.createAsyncProviders = exports.createMikroOrmAsyncOptionsProvider = exports.createEntityManagerProvider = exports.createMikroOrmProvider = void 0;
4
4
  const mikro_orm_common_1 = require("./mikro-orm.common");
5
5
  const core_1 = require("@mikro-orm/core");
6
6
  const common_1 = require("@nestjs/common");
7
- const createMikroOrmProvider = () => ({
8
- provide: core_1.MikroORM,
9
- useFactory: async (options) => {
10
- if (options === null || options === void 0 ? void 0 : options.autoLoadEntities) {
11
- options.entities = [...(options.entities || []), ...mikro_orm_common_1.REGISTERED_ENTITIES.values()];
12
- options.entitiesTs = [...(options.entitiesTs || []), ...mikro_orm_common_1.REGISTERED_ENTITIES.values()];
13
- delete options.autoLoadEntities;
14
- }
15
- mikro_orm_common_1.REGISTERED_ENTITIES.clear();
16
- if (!options || Object.keys(options).length === 0) {
17
- const config = await core_1.ConfigurationLoader.getConfiguration();
18
- config.set('logger', mikro_orm_common_1.logger.log.bind(mikro_orm_common_1.logger));
19
- options = config;
20
- }
21
- return core_1.MikroORM.init(options);
22
- },
23
- inject: [mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS],
24
- });
7
+ const mikro_orm_entities_storage_1 = require("./mikro-orm.entities.storage");
8
+ function createMikroOrmProvider(contextName) {
9
+ return {
10
+ provide: contextName ? (0, mikro_orm_common_1.getMikroORMToken)(contextName) : core_1.MikroORM,
11
+ useFactory: async (options) => {
12
+ if (options?.autoLoadEntities) {
13
+ options.entities = [...(options.entities || []), ...mikro_orm_entities_storage_1.MikroOrmEntitiesStorage.getEntities(contextName)];
14
+ options.entitiesTs = [...(options.entitiesTs || []), ...mikro_orm_entities_storage_1.MikroOrmEntitiesStorage.getEntities(contextName)];
15
+ delete options.autoLoadEntities;
16
+ }
17
+ mikro_orm_entities_storage_1.MikroOrmEntitiesStorage.clear(contextName);
18
+ if (!options || Object.keys(options).length === 0) {
19
+ const config = await core_1.ConfigurationLoader.getConfiguration();
20
+ config.set('logger', mikro_orm_common_1.logger.log.bind(mikro_orm_common_1.logger));
21
+ options = config;
22
+ }
23
+ return core_1.MikroORM.init(options);
24
+ },
25
+ inject: [mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS],
26
+ };
27
+ }
25
28
  exports.createMikroOrmProvider = createMikroOrmProvider;
26
- const createMikroOrmEntityManagerProvider = (scope = common_1.Scope.DEFAULT, entityManager = core_1.EntityManager) => ({
27
- provide: entityManager,
28
- scope,
29
- useFactory: (orm) => scope === common_1.Scope.DEFAULT ? orm.em : orm.em.fork(),
30
- inject: [core_1.MikroORM],
31
- });
32
- exports.createMikroOrmEntityManagerProvider = createMikroOrmEntityManagerProvider;
33
- const createMikroOrmAsyncOptionsProvider = (options) => {
34
- var _a;
29
+ function createEntityManagerProvider(scope = common_1.Scope.DEFAULT, entityManager = core_1.EntityManager, contextName) {
30
+ return {
31
+ provide: contextName ? (0, mikro_orm_common_1.getEntityManagerToken)(contextName) : entityManager,
32
+ scope,
33
+ useFactory: (orm) => scope === common_1.Scope.DEFAULT ? orm.em : orm.em.fork(),
34
+ inject: [contextName ? (0, mikro_orm_common_1.getMikroORMToken)(contextName) : core_1.MikroORM],
35
+ };
36
+ }
37
+ exports.createEntityManagerProvider = createEntityManagerProvider;
38
+ function createMikroOrmAsyncOptionsProvider(options) {
35
39
  if (options.useFactory) {
36
40
  return {
37
41
  provide: mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS,
@@ -41,46 +45,47 @@ const createMikroOrmAsyncOptionsProvider = (options) => {
41
45
  }
42
46
  const inject = [];
43
47
  if (options.useClass || options.useExisting) {
44
- inject.push((_a = options.useClass) !== null && _a !== void 0 ? _a : options.useExisting);
48
+ inject.push(options.useClass ?? options.useExisting);
45
49
  }
46
50
  return {
47
51
  provide: mikro_orm_common_1.MIKRO_ORM_MODULE_OPTIONS,
48
52
  useFactory: async (optionsFactory) => await optionsFactory.createMikroOrmOptions(),
49
53
  inject,
50
54
  };
51
- };
55
+ }
52
56
  exports.createMikroOrmAsyncOptionsProvider = createMikroOrmAsyncOptionsProvider;
53
- const createAsyncProviders = (options) => {
57
+ function createAsyncProviders(options) {
54
58
  if (options.useExisting || options.useFactory) {
55
- return [exports.createMikroOrmAsyncOptionsProvider(options)];
59
+ return [createMikroOrmAsyncOptionsProvider(options)];
56
60
  }
57
61
  if (options.useClass) {
58
62
  return [
59
- exports.createMikroOrmAsyncOptionsProvider(options),
63
+ createMikroOrmAsyncOptionsProvider(options),
60
64
  { provide: options.useClass, useClass: options.useClass },
61
65
  ];
62
66
  }
63
67
  throw new Error('Invalid MikroORM async options: one of `useClass`, `useExisting` or `useFactory` should be defined.');
64
- };
68
+ }
65
69
  exports.createAsyncProviders = createAsyncProviders;
66
- const createMikroOrmRepositoryProviders = (entities) => {
70
+ function createMikroOrmRepositoryProviders(entities, contextName) {
67
71
  const metadata = Object.values(core_1.MetadataStorage.getMetadata());
68
72
  const providers = [];
73
+ const inject = contextName ? (0, mikro_orm_common_1.getEntityManagerToken)(contextName) : core_1.EntityManager;
69
74
  (entities || []).forEach(entity => {
70
75
  const meta = metadata.find(meta => meta.class === entity);
71
- if (meta === null || meta === void 0 ? void 0 : meta.customRepository) {
76
+ if (meta?.customRepository) {
72
77
  providers.push({
73
78
  provide: meta.customRepository(),
74
79
  useFactory: em => em.getRepository(entity),
75
- inject: [core_1.EntityManager],
80
+ inject: [inject],
76
81
  });
77
82
  }
78
83
  providers.push({
79
- provide: mikro_orm_common_1.getRepositoryToken(entity),
84
+ provide: (0, mikro_orm_common_1.getRepositoryToken)(entity, contextName),
80
85
  useFactory: em => em.getRepository(entity),
81
- inject: [core_1.EntityManager],
86
+ inject: [inject],
82
87
  });
83
88
  });
84
89
  return providers;
85
- };
90
+ }
86
91
  exports.createMikroOrmRepositoryProviders = createMikroOrmRepositoryProviders;
@@ -0,0 +1,7 @@
1
+ import type { MikroORM } from '@mikro-orm/core';
2
+ import type { NestMiddleware } from '@nestjs/common';
3
+ export declare class MultipleMikroOrmMiddleware implements NestMiddleware {
4
+ private readonly orm;
5
+ constructor(orm: MikroORM[]);
6
+ use(req: unknown, res: unknown, next: (...args: any[]) => void): void;
7
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MultipleMikroOrmMiddleware = void 0;
16
+ const core_1 = require("@mikro-orm/core");
17
+ const common_1 = require("@nestjs/common");
18
+ let MultipleMikroOrmMiddleware = class MultipleMikroOrmMiddleware {
19
+ constructor(orm) {
20
+ this.orm = orm;
21
+ }
22
+ use(req, res, next) {
23
+ core_1.RequestContext.create(this.orm.map(orm => orm.em), next);
24
+ }
25
+ };
26
+ MultipleMikroOrmMiddleware = __decorate([
27
+ (0, common_1.Injectable)(),
28
+ __param(0, (0, common_1.Inject)('MikroORMs')),
29
+ __metadata("design:paramtypes", [Array])
30
+ ], MultipleMikroOrmMiddleware);
31
+ exports.MultipleMikroOrmMiddleware = MultipleMikroOrmMiddleware;
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@mikro-orm/nestjs",
3
- "version": "4.3.0",
3
+ "version": "5.0.1",
4
4
  "license": "MIT",
5
5
  "author": {
6
- "name": "Dario Mancuso",
7
- "email": "dario@ewide.eu"
6
+ "name": "Martin Adamek",
7
+ "email": "banan23@gmail.com"
8
8
  },
9
9
  "keywords": [
10
10
  "nestjs",
@@ -37,55 +37,52 @@
37
37
  "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 1",
38
38
  "release": "yarn build && cd dist && npm publish && cd ..",
39
39
  "coverage": "yarn test --coverage",
40
- "coveralls": "cat ./coverage/lcov.info | coveralls",
41
40
  "lint": "eslint src/**/*.ts"
42
41
  },
43
42
  "peerDependencies": {
44
- "@mikro-orm/core": "^4.0.0",
45
- "@nestjs/common": "^7.0.0||^8.0.0",
46
- "@nestjs/core": "^7.0.0||^8.0.0"
43
+ "@mikro-orm/core": "^5.0.0",
44
+ "@mikro-orm/knex": "^5.0.0",
45
+ "@mikro-orm/mongodb": "^5.0.0",
46
+ "@nestjs/common": "^8.0.0",
47
+ "@nestjs/core": "^8.0.0"
47
48
  },
48
- "devDependencies": {
49
- "@mikro-orm/core": "^4.5.7",
50
- "@mikro-orm/sqlite": "^4.5.7",
51
- "@nestjs/common": "^8.0.6",
52
- "@nestjs/core": "^8.0.6",
53
- "@nestjs/testing": "^8.0.6",
54
- "@types/jest": "^26.0.10",
55
- "@typescript-eslint/eslint-plugin": "~3.9.1",
56
- "@typescript-eslint/parser": "~3.9.1",
57
- "conventional-changelog": "^3.1.23",
58
- "conventional-changelog-cli": "^2.1.1",
59
- "eslint": "^7.7.0",
60
- "eslint-plugin-jsdoc": "^30.2.4",
61
- "jest": "^26.4.0",
62
- "rxjs": "^6.6.2",
63
- "ts-jest": "^26.2.0",
64
- "typescript": "4.3.5"
49
+ "peerDependenciesMeta": {
50
+ "@mikro-orm/knex": {
51
+ "optional": true
52
+ },
53
+ "@mikro-orm/mongodb": {
54
+ "optional": true
55
+ }
65
56
  },
66
- "jest": {
67
- "testTimeout": 30000,
68
- "preset": "ts-jest",
69
- "collectCoverage": false,
70
- "collectCoverageFrom": [
71
- "<rootDir>/src/**/*.ts"
72
- ],
73
- "modulePathIgnorePatterns": [
74
- "dist/package.json",
75
- "<rootDir>/package.json"
76
- ]
57
+ "devDependencies": {
58
+ "@mikro-orm/core": "^5.0.3",
59
+ "@mikro-orm/sqlite": "^5.0.3",
60
+ "@mikro-orm/mongodb": "^5.0.3",
61
+ "@mikro-orm/knex": "^5.0.3",
62
+ "@nestjs/common": "^8.2.6",
63
+ "@nestjs/core": "^8.2.6",
64
+ "@nestjs/platform-express": "^8.2.6",
65
+ "@nestjs/testing": "^8.2.6",
66
+ "@types/jest": "^27.4.0",
67
+ "@types/node": "^17.0.17",
68
+ "@types/supertest": "^2.0.11",
69
+ "@typescript-eslint/eslint-plugin": "~5.14.0",
70
+ "@typescript-eslint/parser": "~5.14.0",
71
+ "conventional-changelog": "^3.1.25",
72
+ "conventional-changelog-cli": "^2.2.2",
73
+ "eslint": "^8.9.0",
74
+ "jest": "^27.5.1",
75
+ "rxjs": "^7.5.4",
76
+ "supertest": "^6.2.2",
77
+ "ts-jest": "^27.1.3",
78
+ "ts-node": "^10.5.0",
79
+ "typescript": "4.6.2"
77
80
  },
78
81
  "commitlint": {
79
82
  "extends": [
80
83
  "@commitlint/config-conventional"
81
84
  ]
82
85
  },
83
- "husky": {
84
- "hooks": {
85
- "pre-commit": "lint-staged",
86
- "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
87
- }
88
- },
89
86
  "lint-staged": {
90
87
  "*.ts": [
91
88
  "eslint src/**/*.ts --fix"
@@ -93,11 +90,30 @@
93
90
  },
94
91
  "renovate": {
95
92
  "extends": [
96
- "config:base"
93
+ "config:base",
94
+ ":preserveSemverRanges",
95
+ ":semanticCommitTypeAll(chore)"
97
96
  ],
98
- "pinVersions": false
97
+ "semanticCommits": "enabled",
98
+ "separateMajorMinor": false,
99
+ "dependencyDashboard": false,
100
+ "packageRules": [
101
+ {
102
+ "matchUpdateTypes": [
103
+ "patch",
104
+ "minor"
105
+ ],
106
+ "groupName": "patch/minor dependencies",
107
+ "groupSlug": "all-non-major",
108
+ "automerge": true,
109
+ "automergeType": "branch"
110
+ }
111
+ ],
112
+ "schedule": [
113
+ "every weekday"
114
+ ]
99
115
  },
100
116
  "engines": {
101
- "node": ">= 10.13.0"
117
+ "node": ">= 14.0.0"
102
118
  }
103
119
  }
package/typings.d.ts CHANGED
@@ -1,15 +1,13 @@
1
- import { IDatabaseDriver, Options } from '@mikro-orm/core';
2
- import { MiddlewareConsumer, ModuleMetadata, Scope, Type } from '@nestjs/common';
3
- import { AbstractHttpAdapter } from '@nestjs/core';
1
+ import type { AnyEntity, EntityName, IDatabaseDriver, Options } from '@mikro-orm/core';
2
+ import type { MiddlewareConsumer, ModuleMetadata, Scope, Type } from '@nestjs/common';
3
+ import type { AbstractHttpAdapter } from '@nestjs/core';
4
4
  export interface NestMiddlewareConsumer extends MiddlewareConsumer {
5
5
  httpAdapter: AbstractHttpAdapter;
6
6
  }
7
7
  declare type MikroOrmNestScopeOptions = {
8
8
  scope?: Scope;
9
9
  };
10
- export declare type MikroOrmModuleOptions<D extends IDatabaseDriver = IDatabaseDriver> = {
11
- registerRequestContext?: boolean;
12
- autoLoadEntities?: boolean;
10
+ export declare type MikroOrmMiddlewareModuleOptions = {
13
11
  /**
14
12
  * Routes to apply the middleware.
15
13
  *
@@ -18,16 +16,25 @@ export declare type MikroOrmModuleOptions<D extends IDatabaseDriver = IDatabaseD
18
16
  * For all other frameworks including Express, the middleware applies to all routes using `*`.
19
17
  */
20
18
  forRoutesPath?: string;
21
- } & Options<D>;
19
+ };
20
+ export declare type MikroOrmModuleOptions<D extends IDatabaseDriver = IDatabaseDriver> = {
21
+ registerRequestContext?: boolean;
22
+ autoLoadEntities?: boolean;
23
+ } & Options<D> & MikroOrmMiddlewareModuleOptions;
24
+ export interface MikroOrmModuleFeatureOptions {
25
+ entities?: EntityName<AnyEntity>[];
26
+ contextName?: string;
27
+ }
22
28
  export interface MikroOrmOptionsFactory<D extends IDatabaseDriver = IDatabaseDriver> {
23
29
  createMikroOrmOptions(): Promise<MikroOrmModuleOptions<D>> | MikroOrmModuleOptions<D>;
24
30
  }
25
31
  export interface MikroOrmModuleSyncOptions extends MikroOrmModuleOptions, MikroOrmNestScopeOptions {
26
32
  }
27
33
  export interface MikroOrmModuleAsyncOptions<D extends IDatabaseDriver = IDatabaseDriver> extends Pick<ModuleMetadata, 'imports' | 'providers'>, MikroOrmNestScopeOptions {
34
+ contextName?: string;
28
35
  useExisting?: Type<MikroOrmOptionsFactory<D>>;
29
36
  useClass?: Type<MikroOrmOptionsFactory<D>>;
30
- useFactory?: (...args: any[]) => Promise<MikroOrmModuleOptions<D>> | MikroOrmModuleOptions<D>;
37
+ useFactory?: (...args: any[]) => Promise<Omit<MikroOrmModuleOptions<D>, 'contextName'>> | Omit<MikroOrmModuleOptions<D>, 'contextName'>;
31
38
  inject?: any[];
32
39
  }
33
40
  export {};