@artenc/nest-orm 2.0.1 → 2.1.0

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
@@ -21,18 +21,41 @@ npm install @artenc/nest-orm
21
21
 
22
22
  ### `OrmModule`
23
23
 
24
- Import once, wherever you register `TransactionService`'s consumers (typically your root module or a shared database module):
24
+ The application imports `OrmModule.forRoot()` or `OrmModule.forRootAsync()` once. They take the same options as `TypeOrmModule.forRoot()`/`forRootAsync()` and set up the TypeORM connection, so the application doesn't import `TypeOrmModule.forRoot*()` itself:
25
25
 
26
26
  ```ts
27
27
  import { Module } from '@nestjs/common'
28
+ import { ConfigModule, ConfigService } from '@nestjs/config'
28
29
  import { OrmModule } from '@artenc/nest-orm'
29
30
 
30
31
  @Module({
31
- imports: [OrmModule],
32
+ imports: [
33
+ OrmModule.forRootAsync({
34
+ imports: [ConfigModule],
35
+ inject: [ConfigService],
36
+ useFactory: (configService: ConfigService) => ({
37
+ type: 'mysql',
38
+ host: configService.getOrThrow<string>('db.host'),
39
+ // ...
40
+ autoLoadEntities: true,
41
+ }),
42
+ utc: true,
43
+ }),
44
+ ],
32
45
  })
33
46
  export class AppModule {}
34
47
  ```
35
48
 
49
+ Feature modules and libraries that need `TransactionService` import `OrmModule` itself, without options. `OrmModule.forRoot*()` re-exports that same module, so the application and all libraries share one `TransactionService`.
50
+
51
+ With `utc: true`, the connection uses a [`UtcDataSource`](#utcdatasource). `utc` can't be combined with a custom `dataSourceFactory`.
52
+
53
+ ### `UtcDataSource`
54
+
55
+ A `DataSource` that stores and reads dates as UTC (`timezone: 'Z'`), and fails to initialize unless the database server runs in UTC too. The server fills `DEFAULT CURRENT_TIMESTAMP` columns such as `@CreateDateColumn()` in its own time zone, so the server and the driver must agree; otherwise those dates are off by the server's offset. Configure the server with `default-time-zone = '+00:00'`.
56
+
57
+ Supports MySQL and MariaDB; other databases are refused. `OrmModule.forRootAsync({ utc: true })` uses it for the application, and the [DataSource file](#datasource-file-example) can use it for TypeORM's CLI.
58
+
36
59
  ### `AbstractOrmEntity`
37
60
 
38
61
  An entity loaded or created through `AbstractOrmService` doesn't know, from the caller's side, whether it came from its repository or from an active `TransactionService` transaction — it's just an entity. `AbstractOrmEntity` is what makes that transparent: every entity gets a `save()` method that checks, at the moment it's called, whether a transaction is currently active and writes through it if so — joining whatever transaction is running *then*, regardless of whether one was active when the entity was originally loaded or created. If nothing is active at that moment, it falls back to a plain write through the entity's repository instead. Either way, there's no `EntityManager` to pass around by hand.
@@ -200,7 +223,7 @@ Typical TypeORM CLI scripts for a project consuming this library:
200
223
 
201
224
  ## DataSource file example
202
225
 
203
- The `-d dist/data-source.js` flag in the scripts above points TypeORM's CLI at this file: a plain, standalone `DataSource` instance the CLI can import and connect with directly. It's separate from the `DataSource` your NestJS app builds via `TypeOrmModule.forRoot(...)` because the CLI runs as its own process outside Nest's DI container — `migration:generate`/`migration:run`/`migration:revert`/`query` have no other way to reach the same database connection your app uses at runtime.
226
+ The `-d dist/data-source.js` flag in the scripts above points TypeORM's CLI at this file: a plain, standalone `DataSource` instance the CLI can import and connect with directly. It's separate from the `DataSource` your NestJS app builds via `OrmModule.forRoot(...)` because the CLI runs as its own process outside Nest's DI container — `migration:generate`/`migration:run`/`migration:revert`/`query` have no other way to reach the same database connection your app uses at runtime.
204
227
 
205
228
  orm-imports.ts — glob paths TypeORM expands at runtime to every compiled entity/migration file, so `data-source.ts` doesn't need to list them by hand:
206
229
  ```ts
@@ -210,13 +233,13 @@ export const entities = [path.join(__dirname, 'entities/*')]
210
233
  export const migrations = [path.join(__dirname, 'migrations/*')]
211
234
  ```
212
235
 
213
- data-source.ts:
236
+ data-source.ts (with `utc: true` in the application, use `UtcDataSource` here too, so migrations run with the same time zone handling):
214
237
  ```ts
215
238
  import 'dotenv/config'
216
- import { DataSource } from 'typeorm'
239
+ import { UtcDataSource } from '@artenc/nest-orm'
217
240
  import { entities, migrations } from './orm-imports'
218
241
 
219
- export default new DataSource({
242
+ export default new UtcDataSource({
220
243
  type: 'mysql',
221
244
  host: process.env.DB_HOST,
222
245
  port: Number(process.env.DB_PORT),
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ export { BinaryUuidColumn, BinaryUuidOptions, BinaryUuidVersion, binaryUuidTrans
2
2
  export { AbstractOrmEntity } from './entities/abstract-orm.entity';
3
3
  export { AbstractOrmService, IOrmService } from './services/abstract-orm.service';
4
4
  export { TransactionService } from './services/transaction.service';
5
- export { OrmModule } from './orm.module';
5
+ export { UtcDataSource } from './lib/utc-data-source';
6
+ export { OrmModule, OrmModuleAsyncOptions, OrmModuleOptions, OrmUtcOptions } from './orm.module';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OrmModule = exports.TransactionService = exports.AbstractOrmService = exports.AbstractOrmEntity = exports.binaryUuidTransformer = exports.BinaryUuidColumn = void 0;
3
+ exports.OrmModule = exports.UtcDataSource = exports.TransactionService = exports.AbstractOrmService = exports.AbstractOrmEntity = exports.binaryUuidTransformer = exports.BinaryUuidColumn = void 0;
4
4
  var binary_uuid_column_1 = require("./decorators/binary-uuid-column");
5
5
  Object.defineProperty(exports, "BinaryUuidColumn", { enumerable: true, get: function () { return binary_uuid_column_1.BinaryUuidColumn; } });
6
6
  Object.defineProperty(exports, "binaryUuidTransformer", { enumerable: true, get: function () { return binary_uuid_column_1.binaryUuidTransformer; } });
@@ -10,6 +10,8 @@ var abstract_orm_service_1 = require("./services/abstract-orm.service");
10
10
  Object.defineProperty(exports, "AbstractOrmService", { enumerable: true, get: function () { return abstract_orm_service_1.AbstractOrmService; } });
11
11
  var transaction_service_1 = require("./services/transaction.service");
12
12
  Object.defineProperty(exports, "TransactionService", { enumerable: true, get: function () { return transaction_service_1.TransactionService; } });
13
+ var utc_data_source_1 = require("./lib/utc-data-source");
14
+ Object.defineProperty(exports, "UtcDataSource", { enumerable: true, get: function () { return utc_data_source_1.UtcDataSource; } });
13
15
  var orm_module_1 = require("./orm.module");
14
16
  Object.defineProperty(exports, "OrmModule", { enumerable: true, get: function () { return orm_module_1.OrmModule; } });
15
17
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,sEAKwC;AAJpC,sHAAA,gBAAgB,OAAA;AAGhB,2HAAA,qBAAqB,OAAA;AAGzB,sEAAkE;AAAzD,wHAAA,iBAAiB,OAAA;AAE1B,wEAAiF;AAAxE,0HAAA,kBAAkB,OAAA;AAC3B,sEAAmE;AAA1D,yHAAA,kBAAkB,OAAA;AAE3B,2CAAwC;AAA/B,uGAAA,SAAS,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,sEAKwC;AAJpC,sHAAA,gBAAgB,OAAA;AAGhB,2HAAA,qBAAqB,OAAA;AAGzB,sEAAkE;AAAzD,wHAAA,iBAAiB,OAAA;AAE1B,wEAAiF;AAAxE,0HAAA,kBAAkB,OAAA;AAC3B,sEAAmE;AAA1D,yHAAA,kBAAkB,OAAA;AAE3B,yDAAqD;AAA5C,gHAAA,aAAa,OAAA;AAEtB,2CAAgG;AAAvF,uGAAA,SAAS,OAAA"}
@@ -0,0 +1,12 @@
1
+ import { DataSource, DataSourceOptions } from 'typeorm';
2
+ /**
3
+ * A data source that stores and reads dates as UTC, and fails to initialize unless the database server runs in UTC
4
+ * too: the server fills `DEFAULT CURRENT_TIMESTAMP` columns in its own time zone, so both must agree.
5
+ * Databases without UTC handling here are refused.
6
+ */
7
+ export declare class UtcDataSource extends DataSource {
8
+ constructor(options: DataSourceOptions);
9
+ initialize(): Promise<this>;
10
+ private static utcOptions;
11
+ private assertUtcServer;
12
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UtcDataSource = void 0;
4
+ const typeorm_1 = require("typeorm");
5
+ /**
6
+ * A data source that stores and reads dates as UTC, and fails to initialize unless the database server runs in UTC
7
+ * too: the server fills `DEFAULT CURRENT_TIMESTAMP` columns in its own time zone, so both must agree.
8
+ * Databases without UTC handling here are refused.
9
+ */
10
+ class UtcDataSource extends typeorm_1.DataSource {
11
+ constructor(options) {
12
+ super(UtcDataSource.utcOptions(options));
13
+ }
14
+ async initialize() {
15
+ await super.initialize();
16
+ await this.assertUtcServer();
17
+ return this;
18
+ }
19
+ static utcOptions(options) {
20
+ switch (options.type) {
21
+ case 'mysql':
22
+ case 'mariadb':
23
+ return { ...options, timezone: 'Z' };
24
+ default:
25
+ throw new Error(`UtcDataSource doesn't support ${options.type}`);
26
+ }
27
+ }
28
+ async assertUtcServer() {
29
+ switch (this.options.type) {
30
+ case 'mysql':
31
+ case 'mariadb': {
32
+ const [{ offsetSeconds }] = await this.query('SELECT TIMESTAMPDIFF(SECOND, UTC_TIMESTAMP(), NOW()) AS offsetSeconds');
33
+ const offsetMinutes = Math.round(Number(offsetSeconds) / 60);
34
+ if (offsetMinutes !== 0) {
35
+ throw new Error(`The MySQL server's time zone is ${offsetMinutes / 60} hours off UTC; set default-time-zone = '+00:00' in its configuration`);
36
+ }
37
+ return;
38
+ }
39
+ default:
40
+ throw new Error(`UtcDataSource doesn't support ${this.options.type}`);
41
+ }
42
+ }
43
+ }
44
+ exports.UtcDataSource = UtcDataSource;
45
+ //# sourceMappingURL=utc-data-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utc-data-source.js","sourceRoot":"","sources":["../../src/lib/utc-data-source.ts"],"names":[],"mappings":";;;AAAA,qCAAuD;AAEvD;;;;GAIG;AACH,MAAa,aAAc,SAAQ,oBAAU;IACzC,YAAY,OAA0B;QAClC,KAAK,CAAC,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;IAC5C,CAAC;IAEe,KAAK,CAAC,UAAU;QAC5B,MAAM,KAAK,CAAC,UAAU,EAAE,CAAA;QACxB,MAAM,IAAI,CAAC,eAAe,EAAE,CAAA;QAC5B,OAAO,IAAI,CAAA;IACf,CAAC;IAEO,MAAM,CAAC,UAAU,CAAC,OAA0B;QAChD,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,OAAO,CAAC;YACb,KAAK,SAAS;gBACV,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAA;YACxC;gBACI,MAAM,IAAI,KAAK,CAAC,iCAAiC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;QACxE,CAAC;IACL,CAAC;IAEO,KAAK,CAAC,eAAe;QACzB,QAAQ,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;YACxB,KAAK,OAAO,CAAC;YACb,KAAK,SAAS,CAAC,CAAC,CAAC;gBACb,MAAM,CAAC,EAAE,aAAa,EAAE,CAAC,GAAG,MAAM,IAAI,CAAC,KAAK,CACxC,uEAAuE,CAC1E,CAAA;gBACD,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC,CAAA;gBAC5D,IAAI,aAAa,KAAK,CAAC,EAAE,CAAC;oBACtB,MAAM,IAAI,KAAK,CACX,mCAAmC,aAAa,GAAG,EAAE,uEAAuE,CAC/H,CAAA;gBACL,CAAC;gBACD,OAAM;YACV,CAAC;YACD;gBACI,MAAM,IAAI,KAAK,CAAC,iCAAiC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;QAC7E,CAAC;IACL,CAAC;CACJ;AAxCD,sCAwCC"}
@@ -1,2 +1,32 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ import { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';
3
+ export interface OrmUtcOptions {
4
+ /**
5
+ * Stores and reads dates as UTC, and refuses to start unless the database server runs in UTC too
6
+ * (see `UtcDataSource`). Off by default.
7
+ */
8
+ utc?: boolean;
9
+ }
10
+ export type OrmModuleOptions = TypeOrmModuleOptions & OrmUtcOptions;
11
+ export type OrmModuleAsyncOptions = TypeOrmModuleAsyncOptions & OrmUtcOptions;
12
+ /**
13
+ * Sets up the TypeORM connection for `OrmModule.forRoot*()` and re-exports the plain `OrmModule`, so the application
14
+ * and every library share one `OrmModule` and one `TransactionService`.
15
+ */
16
+ export declare class OrmCoreModule {
17
+ }
18
+ /**
19
+ * Provides `TransactionService`. It's imported in one of two ways:
20
+ *
21
+ * - The application imports `OrmModule.forRoot()` or `OrmModule.forRootAsync()` once, typically in its root or a
22
+ * shared database module. This also sets up the TypeORM connection, in place of `TypeOrmModule.forRoot*()`, and can
23
+ * enforce UTC dates with `utc: true`.
24
+ * - Feature modules and libraries import `OrmModule` itself, without options, next to `TypeOrmModule.forFeature()`.
25
+ * They must not call `forRoot*()`: that would open a second connection, with settings only the application has.
26
+ *
27
+ * Both ways resolve to the same module, so the application and every library share one `TransactionService`.
28
+ */
1
29
  export declare class OrmModule {
30
+ static forRoot(options?: OrmModuleOptions): DynamicModule;
31
+ static forRootAsync(options: OrmModuleAsyncOptions): DynamicModule;
2
32
  }
@@ -5,14 +5,62 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
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
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
7
  };
8
+ var OrmModule_1;
8
9
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.OrmModule = void 0;
10
+ exports.OrmModule = exports.OrmCoreModule = void 0;
10
11
  const common_1 = require("@nestjs/common");
12
+ const typeorm_1 = require("@nestjs/typeorm");
13
+ const utc_data_source_1 = require("./lib/utc-data-source");
11
14
  const transaction_service_1 = require("./services/transaction.service");
12
- let OrmModule = class OrmModule {
15
+ /**
16
+ * Sets up the TypeORM connection for `OrmModule.forRoot*()` and re-exports the plain `OrmModule`, so the application
17
+ * and every library share one `OrmModule` and one `TransactionService`.
18
+ */
19
+ let OrmCoreModule = class OrmCoreModule {
20
+ };
21
+ exports.OrmCoreModule = OrmCoreModule;
22
+ exports.OrmCoreModule = OrmCoreModule = __decorate([
23
+ (0, common_1.Module)({})
24
+ ], OrmCoreModule);
25
+ /**
26
+ * Provides `TransactionService`. It's imported in one of two ways:
27
+ *
28
+ * - The application imports `OrmModule.forRoot()` or `OrmModule.forRootAsync()` once, typically in its root or a
29
+ * shared database module. This also sets up the TypeORM connection, in place of `TypeOrmModule.forRoot*()`, and can
30
+ * enforce UTC dates with `utc: true`.
31
+ * - Feature modules and libraries import `OrmModule` itself, without options, next to `TypeOrmModule.forFeature()`.
32
+ * They must not call `forRoot*()`: that would open a second connection, with settings only the application has.
33
+ *
34
+ * Both ways resolve to the same module, so the application and every library share one `TransactionService`.
35
+ */
36
+ let OrmModule = OrmModule_1 = class OrmModule {
37
+ static forRoot(options = {}) {
38
+ const { utc, ...typeOrmOptions } = options;
39
+ return OrmModule_1.forRootAsync({ utc, name: typeOrmOptions.name, useFactory: () => typeOrmOptions });
40
+ }
41
+ static forRootAsync(options) {
42
+ const { utc, ...typeOrmOptions } = options;
43
+ if (utc && typeOrmOptions.dataSourceFactory) {
44
+ throw new Error("OrmModule: `utc` provides the data source, so it can't be combined with `dataSourceFactory`");
45
+ }
46
+ return {
47
+ module: OrmCoreModule,
48
+ imports: [
49
+ OrmModule_1,
50
+ typeorm_1.TypeOrmModule.forRootAsync({
51
+ ...typeOrmOptions,
52
+ // TypeORM's module initializes the returned data source, which runs its UTC check
53
+ ...(utc && {
54
+ dataSourceFactory: (dataSourceOptions) => Promise.resolve(new utc_data_source_1.UtcDataSource(dataSourceOptions)),
55
+ }),
56
+ }),
57
+ ],
58
+ exports: [OrmModule_1],
59
+ };
60
+ }
13
61
  };
14
62
  exports.OrmModule = OrmModule;
15
- exports.OrmModule = OrmModule = __decorate([
63
+ exports.OrmModule = OrmModule = OrmModule_1 = __decorate([
16
64
  (0, common_1.Module)({
17
65
  providers: [transaction_service_1.TransactionService],
18
66
  exports: [transaction_service_1.TransactionService],
@@ -1 +1 @@
1
- {"version":3,"file":"orm.module.js","sourceRoot":"","sources":["../src/orm.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAuC;AACvC,wEAAmE;AAO5D,IAAM,SAAS,GAAf,MAAM,SAAS;CAAG,CAAA;AAAZ,8BAAS;oBAAT,SAAS;IALrB,IAAA,eAAM,EAAC;QACJ,SAAS,EAAE,CAAC,wCAAkB,CAAC;QAE/B,OAAO,EAAE,CAAC,wCAAkB,CAAC;KAChC,CAAC;GACW,SAAS,CAAG"}
1
+ {"version":3,"file":"orm.module.js","sourceRoot":"","sources":["../src/orm.module.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAAsD;AACtD,6CAAgG;AAChG,2DAAqD;AACrD,wEAAmE;AAanE;;;GAGG;AAEI,IAAM,aAAa,GAAnB,MAAM,aAAa;CAAG,CAAA;AAAhB,sCAAa;wBAAb,aAAa;IADzB,IAAA,eAAM,EAAC,EAAE,CAAC;GACE,aAAa,CAAG;AAE7B;;;;;;;;;;GAUG;AAMI,IAAM,SAAS,iBAAf,MAAM,SAAS;IACX,MAAM,CAAC,OAAO,CAAC,UAA4B,EAAE;QAChD,MAAM,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,OAAO,CAAA;QAC1C,OAAO,WAAS,CAAC,YAAY,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,cAAc,EAAE,CAAC,CAAA;IACvG,CAAC;IAEM,MAAM,CAAC,YAAY,CAAC,OAA8B;QACrD,MAAM,EAAE,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,OAAO,CAAA;QAC1C,IAAI,GAAG,IAAI,cAAc,CAAC,iBAAiB,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CACX,6FAA6F,CAChG,CAAA;QACL,CAAC;QAED,OAAO;YACH,MAAM,EAAE,aAAa;YACrB,OAAO,EAAE;gBACL,WAAS;gBACT,uBAAa,CAAC,YAAY,CAAC;oBACvB,GAAG,cAAc;oBACjB,kFAAkF;oBAClF,GAAG,CAAC,GAAG,IAAI;wBACP,iBAAiB,EAAE,CAAC,iBAAiB,EAAE,EAAE,CACrC,OAAO,CAAC,OAAO,CAAC,IAAI,+BAAa,CAAC,iBAAkB,CAAC,CAAC;qBAC7D,CAAC;iBACL,CAAC;aACL;YACD,OAAO,EAAE,CAAC,WAAS,CAAC;SACvB,CAAA;IACL,CAAC;CACJ,CAAA;AA9BY,8BAAS;oBAAT,SAAS;IALrB,IAAA,eAAM,EAAC;QACJ,SAAS,EAAE,CAAC,wCAAkB,CAAC;QAE/B,OAAO,EAAE,CAAC,wCAAkB,CAAC;KAChC,CAAC;GACW,SAAS,CA8BrB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artenc/nest-orm",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Helper utility to work with TypeORM",
5
5
  "keywords": [
6
6
  "nestjs",
@@ -81,7 +81,8 @@
81
81
  "devDependencies": {
82
82
  "@eslint/js": "^9.18.0",
83
83
  "@nestjs/cli": "^11.0.0",
84
- "@nestjs/common": "^11.0.0",
84
+ "@nestjs/common": "^11.2.7",
85
+ "@nestjs/core": "^11.2.7",
85
86
  "@nestjs/schematics": "^11.0.0",
86
87
  "@nestjs/typeorm": "^11.0.0",
87
88
  "@types/jest": "^30.0.0",
@@ -91,6 +92,7 @@
91
92
  "eslint-plugin-prettier": "^5.2.2",
92
93
  "globals": "^16.0.0",
93
94
  "jest": "^30.5.0",
95
+ "mysql2": "^3.24.5",
94
96
  "prettier": "^3.4.2",
95
97
  "reflect-metadata": "^0.2.2",
96
98
  "ts-jest": "^29.4.12",