@tsed/mikro-orm 7.0.0-beta.2 → 7.0.0-beta.20

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.
Files changed (97) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/cjs/MikroOrmModule.d.ts +7 -3
  3. package/lib/cjs/MikroOrmModule.js +30 -12
  4. package/lib/cjs/MikroOrmModule.js.map +1 -1
  5. package/lib/cjs/decorators/entityManager.d.ts +6 -6
  6. package/lib/cjs/decorators/entityManager.js +6 -6
  7. package/lib/cjs/decorators/entityManager.js.map +1 -1
  8. package/lib/cjs/decorators/orm.d.ts +5 -0
  9. package/lib/cjs/decorators/orm.js +12 -0
  10. package/lib/cjs/decorators/orm.js.map +1 -0
  11. package/lib/cjs/decorators/transactional.d.ts +6 -2
  12. package/lib/cjs/decorators/transactional.js +6 -2
  13. package/lib/cjs/decorators/transactional.js.map +1 -1
  14. package/lib/cjs/filters/OptimisticLockErrorFilter.js +1 -1
  15. package/lib/cjs/index.d.ts +12 -4
  16. package/lib/cjs/index.js +13 -5
  17. package/lib/cjs/index.js.map +1 -1
  18. package/lib/cjs/interceptors/TransactionalInterceptor.d.ts +10 -4
  19. package/lib/cjs/interceptors/TransactionalInterceptor.js +56 -40
  20. package/lib/cjs/interceptors/TransactionalInterceptor.js.map +1 -1
  21. package/lib/cjs/package.json +3 -0
  22. package/lib/cjs/services/MikroOrmContext.d.ts +9 -0
  23. package/lib/cjs/services/MikroOrmContext.js +26 -0
  24. package/lib/cjs/services/MikroOrmContext.js.map +1 -0
  25. package/lib/cjs/services/MikroOrmFactory.d.ts +4 -2
  26. package/lib/cjs/services/MikroOrmFactory.js +12 -10
  27. package/lib/cjs/services/MikroOrmFactory.js.map +1 -1
  28. package/lib/cjs/services/MikroOrmRegistry.d.ts +7 -5
  29. package/lib/cjs/services/MikroOrmRegistry.js +32 -27
  30. package/lib/cjs/services/MikroOrmRegistry.js.map +1 -1
  31. package/lib/esm/MikroOrmModule.js +25 -7
  32. package/lib/esm/MikroOrmModule.js.map +1 -1
  33. package/lib/esm/decorators/entityManager.js +6 -6
  34. package/lib/esm/decorators/entityManager.js.map +1 -1
  35. package/lib/esm/decorators/orm.js +8 -0
  36. package/lib/esm/decorators/orm.js.map +1 -0
  37. package/lib/esm/decorators/transactional.js +6 -2
  38. package/lib/esm/decorators/transactional.js.map +1 -1
  39. package/lib/esm/index.js +13 -5
  40. package/lib/esm/index.js.map +1 -1
  41. package/lib/esm/interceptors/TransactionalInterceptor.js +49 -33
  42. package/lib/esm/interceptors/TransactionalInterceptor.js.map +1 -1
  43. package/lib/esm/package.json +3 -0
  44. package/lib/esm/services/MikroOrmContext.js +23 -0
  45. package/lib/esm/services/MikroOrmContext.js.map +1 -0
  46. package/lib/esm/services/MikroOrmFactory.js +12 -10
  47. package/lib/esm/services/MikroOrmFactory.js.map +1 -1
  48. package/lib/esm/services/MikroOrmRegistry.js +29 -24
  49. package/lib/esm/services/MikroOrmRegistry.js.map +1 -1
  50. package/lib/types/MikroOrmModule.d.ts +7 -3
  51. package/lib/types/decorators/entityManager.d.ts +6 -6
  52. package/lib/types/decorators/orm.d.ts +5 -0
  53. package/lib/types/decorators/transactional.d.ts +6 -2
  54. package/lib/types/index.d.ts +12 -4
  55. package/lib/types/interceptors/TransactionalInterceptor.d.ts +10 -4
  56. package/lib/types/services/MikroOrmContext.d.ts +9 -0
  57. package/lib/types/services/MikroOrmFactory.d.ts +4 -2
  58. package/lib/types/services/MikroOrmRegistry.d.ts +7 -5
  59. package/package.json +23 -18
  60. package/readme.md +75 -46
  61. package/tsconfig.compile.esm.json +1 -12
  62. package/lib/cjs/decorators/connection.d.ts +0 -1
  63. package/lib/cjs/decorators/connection.js +0 -8
  64. package/lib/cjs/decorators/connection.js.map +0 -1
  65. package/lib/cjs/decorators/index.d.ts +0 -3
  66. package/lib/cjs/decorators/index.js +0 -7
  67. package/lib/cjs/decorators/index.js.map +0 -1
  68. package/lib/cjs/filters/index.d.ts +0 -1
  69. package/lib/cjs/filters/index.js +0 -5
  70. package/lib/cjs/filters/index.js.map +0 -1
  71. package/lib/cjs/interceptors/index.d.ts +0 -1
  72. package/lib/cjs/interceptors/index.js +0 -5
  73. package/lib/cjs/interceptors/index.js.map +0 -1
  74. package/lib/cjs/services/DBContext.d.ts +0 -9
  75. package/lib/cjs/services/DBContext.js +0 -37
  76. package/lib/cjs/services/DBContext.js.map +0 -1
  77. package/lib/cjs/services/index.d.ts +0 -4
  78. package/lib/cjs/services/index.js +0 -8
  79. package/lib/cjs/services/index.js.map +0 -1
  80. package/lib/esm/decorators/connection.js +0 -4
  81. package/lib/esm/decorators/connection.js.map +0 -1
  82. package/lib/esm/decorators/index.js +0 -4
  83. package/lib/esm/decorators/index.js.map +0 -1
  84. package/lib/esm/filters/index.js +0 -2
  85. package/lib/esm/filters/index.js.map +0 -1
  86. package/lib/esm/interceptors/index.js +0 -2
  87. package/lib/esm/interceptors/index.js.map +0 -1
  88. package/lib/esm/services/DBContext.js +0 -34
  89. package/lib/esm/services/DBContext.js.map +0 -1
  90. package/lib/esm/services/index.js +0 -5
  91. package/lib/esm/services/index.js.map +0 -1
  92. package/lib/types/decorators/connection.d.ts +0 -1
  93. package/lib/types/decorators/index.d.ts +0 -3
  94. package/lib/types/filters/index.d.ts +0 -1
  95. package/lib/types/interceptors/index.d.ts +0 -1
  96. package/lib/types/services/DBContext.d.ts +0 -9
  97. package/lib/types/services/index.d.ts +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"MikroOrmRegistry.js","sourceRoot":"","sources":["../../../src/services/MikroOrmRegistry.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAC,MAAM,EAAE,UAAU,EAAC,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAC,eAAe,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAC;AACrD,OAAO,EAAC,MAAM,EAAC,MAAM,cAAc,CAAC;AAG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GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAoB,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;QAE9G,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC3B,CAAC;IAEO,KAAK,CAAC,OAAO,CAAC,UAAoB;QACxC,IAAI,MAAM,UAAU,CAAC,WAAW,EAAE,EAAE;YAClC,MAAM,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SAC/B;IACH,CAAC;CACF,CAAA;AA9CY,gBAAgB;IAD5B,UAAU,EAAE;IAIE,WAAA,MAAM,EAAE,CAAA;IAAmC,WAAA,MAAM,EAAE,CAAA;qCAAjB,MAAM,EAA8C,eAAe;GAHvG,gBAAgB,CA8C5B;SA9CY,gBAAgB","sourcesContent":["import {MikroOrmFactory} from \"./MikroOrmFactory\";\nimport {Inject, Injectable} from \"@tsed/di\";\nimport {IDatabaseDriver as DatabaseDriver, MikroORM, Options} from \"@mikro-orm/core\";\nimport {catchAsyncError, getValue} from \"@tsed/core\";\nimport {Logger} from \"@tsed/logger\";\n\n@Injectable()\nexport class MikroOrmRegistry {\n private readonly connections = new Map<string, MikroORM>();\n\n constructor(@Inject() private readonly logger: Logger, @Inject() private readonly mikroOrmFactory: MikroOrmFactory) {}\n\n public async createConnection<T extends DatabaseDriver>(connectionOptions: Options<T>): Promise<MikroORM> {\n const connectionName = getValue<string>(connectionOptions, \"contextName\", \"default\");\n\n if (this.has(connectionName)) {\n return this.get(connectionName);\n }\n\n this.logger.info(`Create connection with MikroOrm to database: %s`, connectionName);\n this.logger.debug(`options: %j`, connectionOptions);\n\n const connection = await this.mikroOrmFactory.create(connectionOptions);\n\n this.connections.set(connectionName, connection);\n\n this.logger.info(`Connected with MikroOrm to database: %s`, connectionName);\n\n return connection;\n }\n\n public get(id: string = \"default\"): MikroORM {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.connections.get(id)!;\n }\n\n public has(id: string = \"default\"): boolean {\n return this.connections.has(id);\n }\n\n public async closeConnections(): Promise<void> {\n const connections = [...this.connections.values()];\n\n await Promise.all(connections.map((connection: MikroORM) => catchAsyncError(() => this.dispose(connection))));\n\n this.connections.clear();\n }\n\n private async dispose(connection: MikroORM): Promise<void> {\n if (await connection.isConnected()) {\n await connection.close(false);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"MikroOrmRegistry.js","sourceRoot":"","sources":["../../../src/services/MikroOrmRegistry.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAC,MAAM,EAAE,UAAU,EAAC,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAC,eAAe,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAC;AACrD,OAAO,EAAC,MAAM,EAAC,MAAM,cAAc,CAAC;AAGpC,IAAa,gBAAgB,GAA7B,MAAa,gBAAgB;IAIY;IAA2C;IAHjE,oBAAoB,GAAG,SAAS,CAAC;IACjC,SAAS,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEzD,YAAuC,MAAc,EAA6B,eAAgC;QAA3E,WAAM,GAAN,MAAM,CAAQ;QAA6B,oBAAe,GAAf,eAAe,CAAiB;IAAG,CAAC;IAE/G,KAAK,CAAC,QAAQ,CAA2B,OAAmB;QACjE,MAAM,WAAW,GAAG,QAAQ,CAAS,OAAO,EAAE,aAAa,EAAE,IAAI,CAAC,oBAAoB,CAAC,CAAC;QAExF,IAAI,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACzB,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAE,CAAC;SAC/B;QAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iDAAiD,EAAE,WAAW,CAAC,CAAC;QACjF,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;QA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qCAAjB,MAAM,EAA8C,eAAe;GAJvG,gBAAgB,CAkD5B;SAlDY,gBAAgB","sourcesContent":["import {MikroOrmFactory} from \"./MikroOrmFactory\";\nimport {Inject, Injectable} from \"@tsed/di\";\nimport {IDatabaseDriver as DatabaseDriver, MikroORM, Options} from \"@mikro-orm/core\";\nimport {catchAsyncError, getValue} from \"@tsed/core\";\nimport {Logger} from \"@tsed/logger\";\n\n@Injectable()\nexport class MikroOrmRegistry {\n private readonly DEFAULT_CONTEXT_NAME = \"default\";\n private readonly instances = new Map<string, MikroORM>();\n\n constructor(@Inject() private readonly logger: Logger, @Inject() private readonly mikroOrmFactory: MikroOrmFactory) {}\n\n public async register<T extends DatabaseDriver>(options: Options<T>): Promise<MikroORM> {\n const contextName = getValue<string>(options, \"contextName\", this.DEFAULT_CONTEXT_NAME);\n\n if (this.has(contextName)) {\n return this.get(contextName)!;\n }\n\n this.logger.info(`Create connection with MikroOrm to database: %s`, contextName);\n this.logger.debug(`options: %j`, options);\n\n const instance = await this.mikroOrmFactory.create(options);\n\n this.instances.set(contextName, instance);\n\n this.logger.info(`Connected with MikroOrm to database: %s`, contextName);\n\n return instance;\n }\n\n public get(contextName?: string): MikroORM | undefined {\n return this.instances.get(contextName ?? this.DEFAULT_CONTEXT_NAME);\n }\n\n public has(contextName?: string): boolean {\n return this.instances.has(contextName ?? this.DEFAULT_CONTEXT_NAME);\n }\n\n public values(): IterableIterator<MikroORM> {\n return this.instances.values();\n }\n\n public async clear(): Promise<void> {\n const instances = [...this.instances.values()];\n\n await Promise.all(instances.map((instance: MikroORM) => catchAsyncError(() => this.dispose(instance))));\n\n this.instances.clear();\n }\n\n private async dispose(instance: MikroORM): Promise<void> {\n if (await instance.isConnected()) {\n await instance.close(false);\n }\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
- import { OnDestroy, OnInit } from "@tsed/di";
1
+ import "./services/MikroOrmFactory";
2
+ import { AlterRunInContext, OnDestroy, OnInit } from "@tsed/di";
2
3
  import { Options } from "@mikro-orm/core";
3
4
  declare global {
4
5
  namespace TsED {
@@ -11,9 +12,12 @@ declare global {
11
12
  }
12
13
  }
13
14
  }
14
- export declare class MikroOrmModule implements OnDestroy, OnInit {
15
+ export declare class MikroOrmModule implements OnDestroy, OnInit, AlterRunInContext {
15
16
  private readonly settings;
16
- private readonly mikroOrmRegistry;
17
+ private readonly registry;
18
+ private readonly context;
17
19
  $onInit(): Promise<void>;
18
20
  $onDestroy(): Promise<void>;
21
+ $alterRunInContext(next: (...args: unknown[]) => unknown): () => unknown | Promise<() => unknown>;
22
+ private createContext;
19
23
  }
@@ -1,14 +1,14 @@
1
1
  /**
2
- * Get the entity manager for the given connection name.
3
- * @param connectionName
2
+ * Get the entity manager for the given context name.
3
+ * @param {String} contextName
4
4
  * @decorator
5
5
  * @mikroOrm
6
6
  */
7
- export declare const EntityManager: (connectionName?: string | undefined) => PropertyDecorator;
7
+ export declare const EntityManager: (contextName?: string) => PropertyDecorator;
8
8
  /**
9
- * Get the entity manager for the given connection name.
10
- * @param connectionName
9
+ * Get the entity manager for the given context name.
10
+ * @param {String} connectionName
11
11
  * @decorator
12
12
  * @mikroOrm
13
13
  */
14
- export declare const Em: (connectionName?: string | undefined) => PropertyDecorator;
14
+ export declare const Em: (contextName?: string) => PropertyDecorator;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Get the ORM for the given context name.
3
+ * @param {String} contextName
4
+ */
5
+ export declare const Orm: (contextName?: string) => PropertyDecorator;
@@ -1,2 +1,6 @@
1
- import { TransactionOptions } from "../interceptors";
2
- export declare const Transactional: (connectionOrOptions?: string | TransactionOptions | undefined) => MethodDecorator;
1
+ import { TransactionOptions } from "../interceptors/TransactionalInterceptor";
2
+ /**
3
+ * Register a new request context for your method and execute it inside the context.
4
+ * @param {String | TransactionOptions} contextNameOrOptions
5
+ */
6
+ export declare const Transactional: (contextNameOrOptions?: string | TransactionOptions) => MethodDecorator;
@@ -1,5 +1,13 @@
1
- export * from "./decorators";
2
- export * from "./filters";
3
- export * from "./interceptors";
4
- export * from "./services";
1
+ /**
2
+ * @file Automatically generated by barrelsby.
3
+ */
5
4
  export * from "./MikroOrmModule";
5
+ export * from "./decorators/entityManager";
6
+ export * from "./decorators/orm";
7
+ export * from "./decorators/transactional";
8
+ export * from "./filters/OptimisticLockErrorFilter";
9
+ export * from "./interceptors/TransactionalInterceptor";
10
+ export * from "./services/MikroOrmContext";
11
+ export * from "./services/MikroOrmFactory";
12
+ export * from "./services/MikroOrmRegistry";
13
+ export * from "./services/RetryStrategy";
@@ -1,19 +1,25 @@
1
- import { DBContext, MikroOrmRegistry, RetryStrategy } from "../services";
2
1
  import { InterceptorContext, InterceptorMethods, InterceptorNext } from "@tsed/di";
3
2
  import { Logger } from "@tsed/logger";
3
+ import { RetryStrategy } from "../services/RetryStrategy";
4
+ import { MikroOrmContext } from "../services/MikroOrmContext";
5
+ import { MikroOrmRegistry } from "../services/MikroOrmRegistry";
6
+ import { FlushMode, IsolationLevel } from "@mikro-orm/core";
4
7
  export interface TransactionOptions {
5
- connectionName?: string;
6
8
  retry?: boolean;
9
+ disabled?: boolean;
10
+ isolationLevel?: IsolationLevel;
11
+ flushMode?: FlushMode;
12
+ contextName?: string;
7
13
  }
8
14
  export declare class TransactionalInterceptor implements InterceptorMethods {
9
15
  private readonly registry;
10
16
  private readonly context;
11
17
  private readonly logger;
12
18
  private readonly retryStrategy?;
13
- constructor(registry: MikroOrmRegistry, context: DBContext, logger: Logger, retryStrategy?: RetryStrategy | undefined);
19
+ constructor(registry: MikroOrmRegistry, context: MikroOrmContext, logger: Logger, retryStrategy?: RetryStrategy | undefined);
14
20
  intercept(context: InterceptorContext<unknown>, next: InterceptorNext): Promise<unknown>;
21
+ private runWithinCtx;
15
22
  private runWithinNewCtx;
16
- private runUnderCtx;
17
23
  private extractContextName;
18
24
  private executeInTransaction;
19
25
  }
@@ -0,0 +1,9 @@
1
+ import { EntityManager } from "@mikro-orm/core";
2
+ /**
3
+ * @internal Since 2022-06-20.
4
+ */
5
+ export declare class MikroOrmContext {
6
+ run(managers: EntityManager[], task: (...args: unknown[]) => unknown): Promise<unknown>;
7
+ get(contextName?: string): EntityManager | undefined;
8
+ has(contextName?: string): boolean;
9
+ }
@@ -1,5 +1,7 @@
1
1
  import { MikroORM, Options } from "@mikro-orm/core";
2
+ import { MikroOrmContext } from "./MikroOrmContext";
2
3
  export declare class MikroOrmFactory {
3
- private readonly dbContext;
4
- create(connectionOptions: Options): Promise<MikroORM>;
4
+ private readonly context;
5
+ constructor(context: MikroOrmContext);
6
+ create(options: Options): Promise<MikroORM>;
5
7
  }
@@ -4,11 +4,13 @@ import { Logger } from "@tsed/logger";
4
4
  export declare class MikroOrmRegistry {
5
5
  private readonly logger;
6
6
  private readonly mikroOrmFactory;
7
- private readonly connections;
7
+ private readonly DEFAULT_CONTEXT_NAME;
8
+ private readonly instances;
8
9
  constructor(logger: Logger, mikroOrmFactory: MikroOrmFactory);
9
- createConnection<T extends DatabaseDriver>(connectionOptions: Options<T>): Promise<MikroORM>;
10
- get(id?: string): MikroORM;
11
- has(id?: string): boolean;
12
- closeConnections(): Promise<void>;
10
+ register<T extends DatabaseDriver>(options: Options<T>): Promise<MikroORM>;
11
+ get(contextName?: string): MikroORM | undefined;
12
+ has(contextName?: string): boolean;
13
+ values(): IterableIterator<MikroORM>;
14
+ clear(): Promise<void>;
13
15
  private dispose;
14
16
  }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@tsed/mikro-orm",
3
- "version": "7.0.0-beta.2",
3
+ "version": "7.0.0-beta.20",
4
4
  "description": "MikroORM package for Ts.ED framework",
5
5
  "private": false,
6
6
  "source": "./src/index.ts",
7
7
  "main": "./lib/cjs/index.js",
8
+ "module": "./lib/esm/index.js",
8
9
  "typings": "./lib/types/index.d.ts",
9
10
  "exports": {
10
11
  "types": "./lib/types/index.d.ts",
@@ -13,38 +14,42 @@
13
14
  "default": "./lib/esm/index.js"
14
15
  },
15
16
  "scripts": {
16
- "build": "yarn run build:esm && yarn run build:cjs",
17
+ "build": "yarn barrels && yarn run build:esm && yarn run build:cjs",
17
18
  "build:cjs": "tsc --build tsconfig.compile.json",
18
19
  "build:esm": "tsc --build tsconfig.compile.esm.json",
20
+ "barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\" -e \".benchmark.ts\"",
19
21
  "test": "cross-env NODE_ENV=test jest"
20
22
  },
21
23
  "dependencies": {
22
- "tslib": "2.2.0"
24
+ "tslib": "2.4.0"
23
25
  },
24
26
  "devDependencies": {
25
- "@mikro-orm/core": "^4.5.9",
26
- "@mikro-orm/mongodb": "^4.5.9",
27
- "@tsed/common": "7.0.0-beta.2",
28
- "@tsed/core": "7.0.0-beta.2",
29
- "@tsed/di": "7.0.0-beta.2",
30
- "@tsed/json-mapper": "7.0.0-beta.2",
31
- "@tsed/logger": "^6.0.0",
32
- "@tsed/schema": "7.0.0-beta.2",
33
- "@tsed/testing-mongoose": "7.0.0-beta.2",
27
+ "@mikro-orm/core": "^5.2.2",
28
+ "@mikro-orm/mongodb": "^5.2.2",
29
+ "@tsed/common": "7.0.0-beta.20",
30
+ "@tsed/core": "7.0.0-beta.20",
31
+ "@tsed/di": "7.0.0-beta.20",
32
+ "@tsed/json-mapper": "7.0.0-beta.20",
33
+ "@tsed/logger": ">=6.1.1",
34
+ "@tsed/schema": "7.0.0-beta.20",
35
+ "@tsed/testing-mongoose": "7.0.0-beta.20",
34
36
  "ts-mockito": "^2.6.1"
35
37
  },
36
38
  "peerDependencies": {
37
39
  "@mikro-orm/core": ">=4.5.9",
38
- "@tsed/common": "^7.0.0-beta.2",
39
- "@tsed/core": "^7.0.0-beta.2",
40
- "@tsed/di": "^7.0.0-beta.2",
41
- "@tsed/logger": "^6.0.0"
40
+ "@tsed/common": "^7.0.0-beta.20",
41
+ "@tsed/core": "^7.0.0-beta.20",
42
+ "@tsed/di": "^7.0.0-beta.20",
43
+ "@tsed/logger": ">=6.2.0"
42
44
  },
43
45
  "repository": "https://github.com/tsedio/tsed",
44
46
  "bugs": {
45
47
  "url": "https://github.com/tsedio/tsed/issues"
46
48
  },
47
- "homepage": "https://github.com/tsedio/tsed/tree/alpha/packages/orm/mikro-orm",
49
+ "homepage": "https://github.com/tsedio/tsed/tree/beta/packages/orm/mikro-orm",
48
50
  "author": "Romain Lenzotti",
49
- "license": "MIT"
51
+ "license": "MIT",
52
+ "publishConfig": {
53
+ "tag": "beta"
54
+ }
50
55
  }
package/readme.md CHANGED
@@ -11,7 +11,8 @@
11
11
  [![npm version](https://badge.fury.io/js/%40tsed%2Fcommon.svg)](https://badge.fury.io/js/%40tsed%2Fcommon)
12
12
  [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
13
13
  [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
14
- [![backers](https://opencollective.com/tsed/tiers/badge.svg)](https://opencollective.com/tsed)
14
+ [![github](https://img.shields.io/static/v1?label=Github%20sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/romakita)
15
+ [![opencollective](https://img.shields.io/static/v1?label=OpenCollective%20sponsor&message=%E2%9D%A4&logo=OpenCollective&color=%23fe8e86)](https://opencollective.com/tsed)
15
16
 
16
17
  </div>
17
18
 
@@ -33,13 +34,13 @@ A package of Ts.ED framework. See website: https://tsed.io/tutorials/mikro-orm
33
34
 
34
35
  Currently, `@tsed/mikro-orm` allows you:
35
36
 
36
- - Configure one or more MikroOrm connections via the `@Configuration` decorator. All databases will be initialized
37
+ - Configure one or more MikroORM instances via the `@Configuration` decorator. All databases will be initialized
37
38
  when the server starts during the server's `OnInit` phase.
38
- - Use the Entity MikroOrm as Model for Controllers, AJV Validation and Swagger.
39
+ - Use the Entity MikroORM as Model for Controllers, AJV Validation and Swagger.
39
40
 
40
41
  ## Installation
41
42
 
42
- To begin, install the MikroOrm module for TS.ED:
43
+ To begin, install the MikroORM module for TS.ED:
43
44
 
44
45
  <Tabs class="-code">
45
46
  <Tab label="NPM">
@@ -81,7 +82,7 @@ import {MikroOrmModule} from "@tsed/mikro-orm";
81
82
  ...,
82
83
 
83
84
  entities: [
84
- `${__dirname}/entity/*{.ts,.js}`
85
+ `./entity/*{.ts,.js}`
85
86
  ]
86
87
  },
87
88
  {
@@ -96,32 +97,32 @@ export class Server {}
96
97
 
97
98
  The `mikroOrm` options accepts the same configuration object as `init()` from the MikroORM package. Check [this page](https://mikro-orm.io/docs/configuration) for the complete configuration documentation.
98
99
 
99
- ## Obtain a connection
100
+ ## Obtain ORM instance
100
101
 
101
- `@Connection` decorator lets you retrieve an instance of MikroOrm Connection.
102
+ `@Orm` decorator lets you retrieve an instance of MikroORM.
102
103
 
103
104
  ```typescript
104
105
  import {Injectable, AfterRoutesInit} from "@tsed/common";
105
- import {Connection} from "@tsed/mikro-orm";
106
+ import {Orm} from "@tsed/mikro-orm";
106
107
  import {MikroORM} from "@mikro-orm/core";
107
108
 
108
109
  @Injectable()
109
110
  export class UsersService {
110
- @Connection()
111
- private readonly connection!: MikroORM;
111
+ @Orm()
112
+ private readonly orm!: MikroORM;
112
113
 
113
114
  async create(user: User): Promise<User> {
114
115
  // do something
115
116
  // ...
116
117
  // Then save
117
- await this.connection.em.persistAndFlush(user);
118
+ await this.orm.em.persistAndFlush(user);
118
119
  console.log("Saved a new user with id: " + user.id);
119
120
 
120
121
  return user;
121
122
  }
122
123
 
123
124
  async find(): Promise<User[]> {
124
- const users = await this.connection.em.find(User, {});
125
+ const users = await this.orm.em.find(User, {});
125
126
  console.log("Loaded users: ", users);
126
127
 
127
128
  return users;
@@ -129,15 +130,15 @@ export class UsersService {
129
130
  }
130
131
  ```
131
132
 
132
- It's also possible to inject a connection by his name:
133
+ It's also possible to inject an ORM by its context name:
133
134
 
134
- ```ts
135
+ ```typescript
135
136
  import {Injectable} from "@tsed/di";
136
137
 
137
138
  @Injectable()
138
139
  export class MyService {
139
- @Connection("mongo")
140
- private readonly connection!: MikroORM;
140
+ @Orm("mongo")
141
+ private readonly orm!: MikroORM;
141
142
  }
142
143
  ```
143
144
 
@@ -148,7 +149,7 @@ export class MyService {
148
149
  ```typescript
149
150
  import {Injectable, AfterRoutesInit} from "@tsed/common";
150
151
  import {Em} from "@tsed/mikro-orm";
151
- import {EntityManager} from '@mikro-orm/mysql'; // Import EntityManager from your driver package or `@mikro-orm/knex`
152
+ import {EntityManager} from "@mikro-orm/mysql"; // Import EntityManager from your driver package or `@mikro-orm/knex`
152
153
 
153
154
  @Injectable()
154
155
  export class UsersService {
@@ -164,16 +165,16 @@ export class UsersService {
164
165
  }
165
166
  ```
166
167
 
167
- It's also possible to inject Entity manager by his connection name:
168
+ It's also possible to inject Entity manager by his context name:
168
169
 
169
170
  ```typescript
170
171
  import {Injectable, AfterRoutesInit} from "@tsed/common";
171
172
  import {Em} from "@tsed/mikro-orm";
172
- import {EntityManager} from '@mikro-orm/mysql'; // Import EntityManager from your driver package or `@mikro-orm/knex`
173
+ import {EntityManager} from "@mikro-orm/mysql"; // Import EntityManager from your driver package or `@mikro-orm/knex`
173
174
 
174
175
  @Injectable()
175
176
  export class UsersService {
176
- @Em("connectionName")
177
+ @Em("contextName")
177
178
  private readonly em!: EntityManager;
178
179
 
179
180
  async create(user: User): Promise<User> {
@@ -187,7 +188,7 @@ export class UsersService {
187
188
 
188
189
  ## Use Entity with Controller
189
190
 
190
- To begin, we need to define an Entity MikroOrm like this and use Ts.ED Decorator to define the JSON Schema.
191
+ To begin, we need to define an Entity MikroORM like this and use Ts.ED Decorator to define the JSON Schema.
191
192
 
192
193
  ```typescript
193
194
  import {Property, MaxLength, Required} from "@tsed/common";
@@ -195,31 +196,30 @@ import {Entity, Property, PrimaryKey, Property as Column} from "@mikro-orm/core"
195
196
 
196
197
  @Entity()
197
198
  export class User {
198
-
199
199
  @PrimaryKey()
200
200
  @Property()
201
- id: number;
201
+ id!: number;
202
202
 
203
203
  @Column()
204
204
  @MaxLength(100)
205
205
  @Required()
206
- firstName: string;
206
+ firstName!: string;
207
207
 
208
208
  @Column()
209
209
  @MaxLength(100)
210
210
  @Required()
211
- lastName: string;
211
+ lastName!: string;
212
212
 
213
213
  @Column()
214
214
  @Mininum(0)
215
215
  @Maximum(100)
216
- age: number;
216
+ age!: number;
217
217
  }
218
218
  ```
219
219
 
220
220
  Now, the model is correctly defined and can be used with a [Controller](https://tsed.io/docs/controllers.html)
221
221
  , [AJV validation](tutorials/ajv.md),
222
- [Swagger](tutorials/swagger.md) and [MikroOrm](https://mikro-orm.io/docs/defining-entities).
222
+ [Swagger](tutorials/swagger.md) and [MikroORM](https://mikro-orm.io/docs/defining-entities).
223
223
 
224
224
  We can use this model with a Controller like that:
225
225
 
@@ -229,7 +229,7 @@ import {Controller, Post, BodyParams, Inject, Post, Get} from "@tsed/common";
229
229
  @Controller("/users")
230
230
  export class UsersCtrl {
231
231
  @Inject()
232
- private usersService: UsersService;
232
+ private readonly usersService!: UsersService;
233
233
 
234
234
  @Post("/")
235
235
  create(@BodyParams() user: User): Promise<User> {
@@ -258,7 +258,7 @@ import {Transactional} from "@tsed/mikro-orm";
258
258
  @Controller("/users")
259
259
  export class UsersCtrl {
260
260
  @Inject()
261
- private usersService: UsersService;
261
+ private readonly usersService!: UsersService;
262
262
 
263
263
  @Post("/")
264
264
  @Transactional()
@@ -273,13 +273,49 @@ export class UsersCtrl {
273
273
  }
274
274
  ```
275
275
 
276
+ By default, `IsolationLevel.READ_COMMITTED` is used. You can override it, specifying the isolation level for the transaction by supplying it as the `isolationLevel` parameter in the `@Transactional` decorator:
277
+
278
+ ```typescript
279
+ @Post("/")
280
+ @Transactional({isolationLevel: IsolationLevel.SERIALIZABLE})
281
+ create(@BodyParams() user: User): Promise<User> {
282
+ return this.usersService.create(user);
283
+ }
284
+ ```
285
+
286
+ The MikroORM supports the standard isolation levels such as `SERIALIZABLE` or `REPEATABLE READ`, the full list of available options see [here](https://mikro-orm.io/docs/transactions#isolation-levels).
287
+
288
+ You can also set the [flushing strategy](https://mikro-orm.io/docs/unit-of-work#flush-modes) for the transaction by setting the `flushMode`:
289
+
290
+ ```typescript
291
+ @Post("/")
292
+ @Transactional({flushMode: FlushMode.AUTO})
293
+ create(@BodyParams() user: User): Promise<User> {
294
+ return this.usersService.create(user);
295
+ }
296
+ ```
297
+
298
+ In some cases, you might need to avoid an explicit transaction, but preserve an async context to prevent the usage of the global identity map. For example, starting with v3.4, the MongoDB driver supports transactions. Yet, you have to use a replica set, otherwise, the driver will raise an exception.
299
+
300
+ To prevent `@Transactional()` use of an explicit transaction, you just need to set the `disabled` field to `true`:
301
+
302
+ ```typescript
303
+ @Post("/")
304
+ @Transactional({disabled: true})
305
+ create(@BodyParams() user: User): Promise<User> {
306
+ return this.usersService.create(user);
307
+ }
308
+ ```
309
+
310
+ ## Retry policy
311
+
276
312
  By default, the automatic retry policy is disabled. You can implement your own to match the business requirements and the nature of the failure. For some noncritical operations, it is better to fail as soon as possible rather than retry a coupe of times. For example, in an interactive web application, it is better to fail right after a smaller number of retries with only a short delay between retry attempts, and display a message to the user (for example, "please try again later").
277
313
 
278
314
  The `@Transactional()` decorator allows you to enable a retry policy for the particular resources. You just need to implement the `RetryStrategy` interface and use `registerProvider()` or `@OverrideProvider()` to register it in the IoC container. Below you can find an example to handle occurred optimistic locks based on [an exponential backoff retry strategy](https://en.wikipedia.org/wiki/Exponential_backoff).
279
315
 
280
- ```ts
281
- import { OptimisticLockError } from '@mikro-orm/core';
282
- import { RetryStrategy } from '@tsed/mikro-orm';
316
+ ```typescript
317
+ import {OptimisticLockError} from "@mikro-orm/core";
318
+ import {RetryStrategy} from "@tsed/mikro-orm";
283
319
 
284
320
  export interface ExponentialBackoffOptions {
285
321
  maxDepth: number;
@@ -290,16 +326,11 @@ export class ExponentialBackoff implements RetryStrategy {
290
326
 
291
327
  constructor(private readonly options: ExponentialBackoffOptions) {}
292
328
 
293
- public async acquire<T extends (...args: unknown[]) => unknown>(
294
- task: T
295
- ): Promise<ReturnType<T>> {
329
+ public async acquire<T extends (...args: unknown[]) => unknown>(task: T): Promise<ReturnType<T>> {
296
330
  try {
297
331
  return (await task()) as ReturnType<T>;
298
332
  } catch (e) {
299
- if (
300
- this.shouldRetry(e as Error) &&
301
- this.depth < this.options.maxDepth
302
- ) {
333
+ if (this.shouldRetry(e as Error) && this.depth < this.options.maxDepth) {
303
334
  return this.retry(task);
304
335
  }
305
336
 
@@ -311,9 +342,7 @@ export class ExponentialBackoff implements RetryStrategy {
311
342
  return error instanceof OptimisticLockError;
312
343
  }
313
344
 
314
- private async retry<T extends (...args: unknown[]) => unknown>(
315
- task: T
316
- ): Promise<ReturnType<T>> {
345
+ private async retry<T extends (...args: unknown[]) => unknown>(task: T): Promise<ReturnType<T>> {
317
346
  await this.sleep(2 ** this.depth * 50);
318
347
 
319
348
  this.depth += 1;
@@ -322,14 +351,14 @@ export class ExponentialBackoff implements RetryStrategy {
322
351
  }
323
352
 
324
353
  private sleep(milliseconds: number): Promise<void> {
325
- return new Promise(resolve => setTimeout(resolve, milliseconds));
354
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
326
355
  }
327
356
  }
328
357
 
329
358
  registerProvider({
330
359
  provide: RetryStrategy,
331
360
  useFactory(): ExponentialBackoff {
332
- return new ExponentialBackoff({maxDepth: 3})
361
+ return new ExponentialBackoff({maxDepth: 3});
333
362
  }
334
363
  });
335
364
  ```
@@ -345,7 +374,7 @@ import {Transactional} from "@tsed/mikro-orm";
345
374
  @Controller("/users")
346
375
  export class UsersCtrl {
347
376
  @Inject()
348
- private usersService: UsersService;
377
+ private readonly usersService!: UsersService;
349
378
 
350
379
  @Post("/")
351
380
  @Transactional({retry: true})
@@ -381,7 +410,7 @@ website. [[Become a sponsor](https://opencollective.com/tsed#sponsor)]
381
410
 
382
411
  The MIT License (MIT)
383
412
 
384
- Copyright (c) 2016 - 2018 Romain Lenzotti
413
+ Copyright (c) 2016 - 2022 Romain Lenzotti
385
414
 
386
415
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
387
416
  documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
@@ -8,16 +8,5 @@
8
8
  "declaration": true,
9
9
  "declarationDir": "./lib/types"
10
10
  },
11
- "exclude": [
12
- "node_modules",
13
- "test",
14
- "lib",
15
- "benchmark",
16
- "coverage",
17
- "spec",
18
- "**/*.benchmark.ts",
19
- "**/*.spec.ts",
20
- "keys",
21
- "jest.config.js"
22
- ]
11
+ "exclude": ["node_modules", "test", "lib", "benchmark", "coverage", "spec", "**/*.benchmark.ts", "**/*.spec.ts", "keys", "jest.config.js"]
23
12
  }
@@ -1 +0,0 @@
1
- export declare const Connection: (connectionName?: string | undefined) => PropertyDecorator;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Connection = void 0;
4
- const services_1 = require("../services");
5
- const di_1 = require("@tsed/di");
6
- const Connection = (connectionName) => (0, di_1.Inject)(services_1.MikroOrmRegistry, (registry) => registry.get(connectionName));
7
- exports.Connection = Connection;
8
- //# sourceMappingURL=connection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../../src/decorators/connection.ts"],"names":[],"mappings":";;;AAAA,0CAA6C;AAC7C,iCAAgC;AAEzB,MAAM,UAAU,GAAG,CAAC,cAAuB,EAAqB,EAAE,CACvE,IAAA,WAAM,EAAC,2BAAgB,EAAE,CAAC,QAA0B,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,cAAc,CAAC,CAAsB,CAAC;AADjG,QAAA,UAAU,cACuF","sourcesContent":["import {MikroOrmRegistry} from \"../services\";\nimport {Inject} from \"@tsed/di\";\n\nexport const Connection = (connectionName?: string): PropertyDecorator =>\n Inject(MikroOrmRegistry, (registry: MikroOrmRegistry) => registry.get(connectionName)) as PropertyDecorator;\n"]}
@@ -1,3 +0,0 @@
1
- export * from "./transactional";
2
- export * from "./connection";
3
- export * from "./entityManager";
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- (0, tslib_1.__exportStar)(require("./transactional"), exports);
5
- (0, tslib_1.__exportStar)(require("./connection"), exports);
6
- (0, tslib_1.__exportStar)(require("./entityManager"), exports);
7
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/decorators/index.ts"],"names":[],"mappings":";;;AAAA,+DAAgC;AAChC,4DAA6B;AAC7B,+DAAgC","sourcesContent":["export * from \"./transactional\";\nexport * from \"./connection\";\nexport * from \"./entityManager\";\n"]}
@@ -1 +0,0 @@
1
- export * from "./OptimisticLockErrorFilter";
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- (0, tslib_1.__exportStar)(require("./OptimisticLockErrorFilter"), exports);
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/filters/index.ts"],"names":[],"mappings":";;;AAAA,2EAA4C","sourcesContent":["export * from \"./OptimisticLockErrorFilter\";\n"]}
@@ -1 +0,0 @@
1
- export * from "./TransactionalInterceptor";
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- (0, tslib_1.__exportStar)(require("./TransactionalInterceptor"), exports);
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interceptors/index.ts"],"names":[],"mappings":";;;AAAA,0EAA2C","sourcesContent":["export * from \"./TransactionalInterceptor\";\n"]}