@artenc/nest-orm 1.3.0 → 2.0.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/LICENSE +21 -0
- package/README.md +183 -5
- package/dist/decorators/binary-uuid-column.d.ts +21 -6
- package/dist/decorators/binary-uuid-column.js +41 -27
- package/dist/decorators/binary-uuid-column.js.map +1 -1
- package/dist/entities/abstract-orm.entity.d.ts +3 -2
- package/dist/entities/abstract-orm.entity.js +46 -6
- package/dist/entities/abstract-orm.entity.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/constructor.d.ts +1 -0
- package/dist/lib/constructor.js +3 -0
- package/dist/lib/constructor.js.map +1 -0
- package/dist/lib/transaction-context.d.ts +2 -6
- package/dist/lib/transaction-context.js +3 -0
- package/dist/lib/transaction-context.js.map +1 -1
- package/dist/services/abstract-orm.service.d.ts +2 -3
- package/dist/services/abstract-orm.service.js +32 -61
- package/dist/services/abstract-orm.service.js.map +1 -1
- package/dist/services/transaction.service.d.ts +2 -2
- package/dist/services/transaction.service.js +9 -6
- package/dist/services/transaction.service.js.map +1 -1
- package/dist/utils/generated-column.util.d.ts +9 -0
- package/dist/utils/generated-column.util.js +31 -0
- package/dist/utils/generated-column.util.js.map +1 -0
- package/package.json +69 -5
- package/dist/tsconfig.build.tsbuildinfo +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 artenc
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
# NestJS ORM
|
|
2
2
|
|
|
3
|
-
Helper library to work with TypeORM
|
|
3
|
+
Helper library to work with TypeORM in NestJS: a base entity with a transaction-aware `save()`, a generic CRUD service mixin, a binary UUID column type, and automatic transaction propagation via `AsyncLocalStorage`.
|
|
4
|
+
|
|
5
|
+
## Key features
|
|
6
|
+
|
|
7
|
+
- **Transaction-aware entities** — an entity's `save()` always writes through the right connection, whether that's its repository or an active transaction, with no manual bookkeeping.
|
|
8
|
+
- **Generic CRUD service** — get `create`/`find`/`findOne`/`update`/`remove`/... for an entity without hand-writing the same repository boilerplate every time.
|
|
9
|
+
- **Automatic transaction propagation** — wrap a block of work in a transaction and every entity/service call inside it joins that transaction automatically, including nested calls.
|
|
10
|
+
- **Compact UUID storage** — store UUIDs as 16-byte binary columns instead of 36-character strings, with optional auto-generation.
|
|
4
11
|
|
|
5
12
|
## Installation
|
|
6
13
|
|
|
@@ -8,12 +15,176 @@ Helper library to work with TypeORM.
|
|
|
8
15
|
npm install @artenc/nest-orm
|
|
9
16
|
```
|
|
10
17
|
|
|
18
|
+
`@nestjs/common`, `@nestjs/typeorm`, and `typeorm` are peer dependencies — install them in your app if you haven't already (any NestJS + TypeORM project already has them).
|
|
19
|
+
|
|
11
20
|
## Usage
|
|
12
21
|
|
|
13
|
-
|
|
22
|
+
### `OrmModule`
|
|
23
|
+
|
|
24
|
+
Import once, wherever you register `TransactionService`'s consumers (typically your root module or a shared database module):
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { Module } from '@nestjs/common'
|
|
28
|
+
import { OrmModule } from '@artenc/nest-orm'
|
|
29
|
+
|
|
30
|
+
@Module({
|
|
31
|
+
imports: [OrmModule],
|
|
32
|
+
})
|
|
33
|
+
export class AppModule {}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### `AbstractOrmEntity`
|
|
37
|
+
|
|
38
|
+
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.
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'
|
|
42
|
+
import { AbstractOrmEntity } from '@artenc/nest-orm'
|
|
43
|
+
|
|
44
|
+
@Entity()
|
|
45
|
+
export class User extends AbstractOrmEntity {
|
|
46
|
+
@PrimaryGeneratedColumn()
|
|
47
|
+
id!: number
|
|
48
|
+
|
|
49
|
+
@Column()
|
|
50
|
+
name!: string
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const user = await userOrmService.findOne({ where: { id } })
|
|
56
|
+
|
|
57
|
+
user.name = 'Ada Lovelace'
|
|
58
|
+
await user.save() // joins whatever transaction is active right now — not necessarily the one that loaded `user`
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
You can also override `fillable()` to allow mass-assigning a specific set of fields from untrusted input (e.g. a request DTO) via `apply()`, instead of writing them out by hand one at a time. Its return type is `(keyof this)[]`, not a plain `string[]`, so a typo'd field name is a compile error rather than a silently-dropped field:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
export class User extends AbstractOrmEntity {
|
|
65
|
+
// ...columns
|
|
66
|
+
|
|
67
|
+
protected fillable(): (keyof this)[] {
|
|
68
|
+
return ['email', 'name']
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
user.apply({ name: 'Ada Lovelace', role: 'admin' }) // 'role' is silently ignored, it's not fillable
|
|
75
|
+
await user.save()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### `BinaryUuidColumn`
|
|
79
|
+
|
|
80
|
+
Stores a UUID as a 16-byte `binary` column instead of a 36-character string — smaller and faster to index — and can optionally generate the value for you on insert.
|
|
81
|
+
|
|
82
|
+
**Supported databases: MySQL and SQL Server only.** `BinaryUuidColumn` uses TypeORM's `binary` column type under the hood, which those two dialects support natively — Postgres and SQLite do not support a `binary` column type at all, so a `DataSource` with a `BinaryUuidColumn` entity fails to initialize on either of them.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { Entity, Column } from 'typeorm'
|
|
86
|
+
import { AbstractOrmEntity, BinaryUuidColumn } from '@artenc/nest-orm'
|
|
87
|
+
|
|
88
|
+
@Entity()
|
|
89
|
+
export class User extends AbstractOrmEntity {
|
|
90
|
+
@BinaryUuidColumn({ generated: true, primary: true })
|
|
91
|
+
id!: string
|
|
92
|
+
|
|
93
|
+
@Column()
|
|
94
|
+
name!: string
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`BinaryUuidColumn` accepts the usual TypeORM `ColumnOptions` (`nullable`, `primary`, `unique`, ...) plus:
|
|
99
|
+
|
|
100
|
+
| Option | Default | Description |
|
|
101
|
+
| ----------- | ------- | -------------------------------------------------------------------------- |
|
|
102
|
+
| `generated` | `false` | Auto-generate the value on insert if it's `null`/`undefined`. |
|
|
103
|
+
| `version` | `'v7'` | `'v7'` (time-ordered, recommended for index locality) or `'v4'` (random). |
|
|
104
|
+
|
|
105
|
+
`generated: true` is fully supported through nest-orm's own persistence path — `AbstractOrmService.create()` and `AbstractOrmEntity.save()` — via a `@BeforeInsert` hook defined on `AbstractOrmEntity`, so the entity class needs to extend it for auto-generation to actually run (a plain `AbstractOrmEntity` subclass like the `User` above already satisfies this). It isn't triggered by TypeORM's own `repository.insert()`/`entityManager.insert()` or a raw `createQueryBuilder().insert()` — those bypass entity listeners entirely, so provide the id yourself if you reach for those directly.
|
|
106
|
+
|
|
107
|
+
### `AbstractOrmService`
|
|
108
|
+
|
|
109
|
+
`AbstractOrmService(Entity)` returns a class with `create`, `exists`, `find`, `findOne`, `count`, `update`, `remove`, and `createQueryBuilder` already implemented against `Entity`'s repository — extend it instead of hand-writing the same boilerplate for every entity:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { Injectable } from '@nestjs/common'
|
|
113
|
+
import { AbstractOrmService } from '@artenc/nest-orm'
|
|
114
|
+
import { User } from './user.entity'
|
|
115
|
+
|
|
116
|
+
@Injectable()
|
|
117
|
+
export class UserOrmService extends AbstractOrmService(User) {}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
const user = await userOrmService.create({ email: 'ada@example.com', name: 'Ada' })
|
|
122
|
+
|
|
123
|
+
await userOrmService.findOne({ where: { id: user.id } })
|
|
124
|
+
await userOrmService.find({ where: { name: 'Ada' } })
|
|
125
|
+
await userOrmService.update({ id: user.id }, { name: 'Ada Lovelace' })
|
|
126
|
+
await userOrmService.remove({ id: user.id })
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Register the entity's repository the usual way and provide the service:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { Module } from '@nestjs/common'
|
|
133
|
+
import { TypeOrmModule } from '@nestjs/typeorm'
|
|
134
|
+
import { User } from './entities/user.entity'
|
|
135
|
+
import { UserOrmService } from './services/orm/user-orm.service'
|
|
136
|
+
|
|
137
|
+
@Module({
|
|
138
|
+
imports: [TypeOrmModule.forFeature([User])],
|
|
139
|
+
providers: [UserOrmService],
|
|
140
|
+
exports: [UserOrmService],
|
|
141
|
+
})
|
|
142
|
+
export class UserModule {}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Every method takes an optional trailing `enforceEntityManager` argument to run against a specific `EntityManager` instead of the entity's default repository — useful outside of `TransactionService` (e.g. a manually managed `QueryRunner`).
|
|
146
|
+
|
|
147
|
+
### `TransactionService`
|
|
148
|
+
|
|
149
|
+
Wraps a block of work in a real database transaction and makes the transaction's `EntityManager` ambiently available (via `AsyncLocalStorage`) to every `AbstractOrmService`/`AbstractOrmEntity` call made inside it — no need to thread an `EntityManager` through every method call by hand:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { Injectable } from '@nestjs/common'
|
|
153
|
+
import { TransactionService } from '@artenc/nest-orm'
|
|
154
|
+
import { WalletService } from './wallet.service'
|
|
155
|
+
|
|
156
|
+
@Injectable()
|
|
157
|
+
export class TransferService {
|
|
158
|
+
constructor(
|
|
159
|
+
private readonly transactionService: TransactionService,
|
|
160
|
+
private readonly walletService: WalletService,
|
|
161
|
+
) {}
|
|
162
|
+
|
|
163
|
+
async transfer(fromUserId: string, toUserId: string, amount: number): Promise<void> {
|
|
164
|
+
await this.transactionService.transaction(async () => {
|
|
165
|
+
// Both calls below automatically join the same transaction,
|
|
166
|
+
// and roll back together if either one throws.
|
|
167
|
+
await this.walletService.debit(fromUserId, amount)
|
|
168
|
+
await this.walletService.credit(toUserId, amount)
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Calling `transaction()` again while one is already active (e.g. a service method that also wraps its own logic in a transaction, called from inside another transaction) opens a real nested transaction backed by a SQL `SAVEPOINT` — if the inner call fails, only its own work rolls back; the outer transaction is unaffected and can continue.
|
|
175
|
+
|
|
176
|
+
`fn` also receives the active `EntityManager` as an argument, for cases that need it directly — raw TypeORM repositories, `createQueryBuilder()`, or any third-party code expecting an `EntityManager` — instead of relying on `AbstractOrmService`/`AbstractOrmEntity`'s automatic pickup:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
await this.transactionService.transaction(async (manager) => {
|
|
180
|
+
await manager.createQueryBuilder(User, 'user').where('user.id = :id', { id }).getOne()
|
|
181
|
+
})
|
|
182
|
+
```
|
|
14
183
|
|
|
15
184
|
## Scripts
|
|
16
185
|
|
|
186
|
+
Typical TypeORM CLI scripts for a project consuming this library:
|
|
187
|
+
|
|
17
188
|
```json
|
|
18
189
|
{
|
|
19
190
|
"scripts": {
|
|
@@ -29,15 +200,22 @@ Use abstract entity and service classes for base functionality.
|
|
|
29
200
|
|
|
30
201
|
## DataSource file example
|
|
31
202
|
|
|
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.
|
|
204
|
+
|
|
205
|
+
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
|
+
```ts
|
|
207
|
+
import * as path from 'path'
|
|
208
|
+
|
|
209
|
+
export const entities = [path.join(__dirname, 'entities/*')]
|
|
210
|
+
export const migrations = [path.join(__dirname, 'migrations/*')]
|
|
211
|
+
```
|
|
212
|
+
|
|
32
213
|
data-source.ts:
|
|
33
214
|
```ts
|
|
34
215
|
import 'dotenv/config'
|
|
35
216
|
import { DataSource } from 'typeorm'
|
|
36
217
|
import { entities, migrations } from './orm-imports'
|
|
37
218
|
|
|
38
|
-
console.log('Entities:', entities)
|
|
39
|
-
console.log('Migrations:', migrations)
|
|
40
|
-
|
|
41
219
|
export default new DataSource({
|
|
42
220
|
type: 'mysql',
|
|
43
221
|
host: process.env.DB_HOST,
|
|
@@ -1,7 +1,22 @@
|
|
|
1
|
-
import { ColumnOptions } from 'typeorm';
|
|
2
|
-
export
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { ColumnOptions, ValueTransformer } from 'typeorm';
|
|
2
|
+
export type BinaryUuidOptions = Omit<ColumnOptions, 'type' | 'length' | 'transformer' | 'default'> & {
|
|
3
|
+
/**
|
|
4
|
+
* If true, the UUID will be generated automatically on insert.
|
|
5
|
+
*
|
|
6
|
+
* Supported through nest-orm's own persistence path: `AbstractOrmService.create()` and
|
|
7
|
+
* `AbstractOrmEntity.save()` (both go through TypeORM's `.save()`, which runs this generation).
|
|
8
|
+
* Not supported through TypeORM's own `repository.insert()`/`entityManager.insert()` or a raw
|
|
9
|
+
* `createQueryBuilder().insert()` — those bypass entity listeners entirely, so the column would
|
|
10
|
+
* be left unset. Provide the id yourself for those.
|
|
11
|
+
*/
|
|
12
|
+
generated?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The UUID version to use for generation.
|
|
15
|
+
* v7 is recommended for better index performance.
|
|
16
|
+
* @default 'v7'
|
|
17
|
+
*/
|
|
18
|
+
version?: BinaryUuidVersion;
|
|
6
19
|
};
|
|
7
|
-
export
|
|
20
|
+
export type BinaryUuidVersion = 'v4' | 'v7';
|
|
21
|
+
export declare function BinaryUuidColumn(options?: BinaryUuidOptions): PropertyDecorator;
|
|
22
|
+
export declare const binaryUuidTransformer: ValueTransformer;
|
|
@@ -1,38 +1,49 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.binaryUuidTransformer = void 0;
|
|
3
4
|
exports.BinaryUuidColumn = BinaryUuidColumn;
|
|
5
|
+
const crypto_1 = require("crypto");
|
|
4
6
|
const typeorm_1 = require("typeorm");
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
7
|
+
const uuid_1 = require("uuid");
|
|
8
|
+
const generated_column_util_1 = require("../utils/generated-column.util");
|
|
9
|
+
function BinaryUuidColumn(options) {
|
|
10
|
+
const { generated = false, version = 'v7', ...rest } = options ?? {};
|
|
11
|
+
return (target, propertyKey) => {
|
|
12
|
+
// Always registered (even when generated is false) so that a subclass redeclaring this
|
|
13
|
+
// column without `generated: true` can explicitly opt out of an ancestor's auto-generation,
|
|
14
|
+
// rather than silently inheriting it because the subclass "said nothing" about the property.
|
|
15
|
+
(0, generated_column_util_1.addGeneratedColumn)(target.constructor, {
|
|
16
|
+
propertyKey: String(propertyKey),
|
|
17
|
+
generator: generated
|
|
18
|
+
? () => {
|
|
19
|
+
switch (version) {
|
|
20
|
+
case 'v4':
|
|
21
|
+
return (0, crypto_1.randomUUID)();
|
|
22
|
+
case 'v7':
|
|
23
|
+
return (0, uuid_1.v7)();
|
|
24
|
+
default:
|
|
25
|
+
throw new Error(`Unsupported BinaryUuidColumn version: ${String(version)}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
: null,
|
|
29
|
+
});
|
|
30
|
+
(0, typeorm_1.Column)({
|
|
31
|
+
...rest,
|
|
32
|
+
type: 'binary',
|
|
33
|
+
length: 16,
|
|
34
|
+
transformer: exports.binaryUuidTransformer,
|
|
35
|
+
})(target, propertyKey);
|
|
36
|
+
};
|
|
15
37
|
}
|
|
16
|
-
|
|
17
|
-
const value = uuid.toLowerCase();
|
|
18
|
-
const compact = value.replace(/-/g, '');
|
|
19
|
-
if (!/^[0-9a-f]{32}$/.test(compact)) {
|
|
20
|
-
throw new Error(`Invalid UUID: ${uuid}`);
|
|
21
|
-
}
|
|
22
|
-
return [
|
|
23
|
-
compact.slice(0, 8),
|
|
24
|
-
compact.slice(8, 12),
|
|
25
|
-
compact.slice(12, 16),
|
|
26
|
-
compact.slice(16, 20),
|
|
27
|
-
compact.slice(20, 32),
|
|
28
|
-
].join('-');
|
|
29
|
-
}
|
|
30
|
-
const binaryUuidTransformer = {
|
|
38
|
+
exports.binaryUuidTransformer = {
|
|
31
39
|
to(value) {
|
|
32
40
|
if (value == null) {
|
|
33
41
|
return null;
|
|
34
42
|
}
|
|
35
|
-
const compact =
|
|
43
|
+
const compact = value.toLowerCase().replace(/-/g, '');
|
|
44
|
+
if (!/^[0-9a-f]{32}$/.test(compact)) {
|
|
45
|
+
throw new Error(`Invalid UUID: ${value}`);
|
|
46
|
+
}
|
|
36
47
|
return Buffer.from(compact, 'hex');
|
|
37
48
|
},
|
|
38
49
|
from(value) {
|
|
@@ -40,7 +51,10 @@ const binaryUuidTransformer = {
|
|
|
40
51
|
return null;
|
|
41
52
|
}
|
|
42
53
|
const hex = value.toString('hex');
|
|
43
|
-
return
|
|
54
|
+
return formatUuid(hex);
|
|
44
55
|
},
|
|
45
56
|
};
|
|
57
|
+
function formatUuid(hex) {
|
|
58
|
+
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20, 32)].join('-');
|
|
59
|
+
}
|
|
46
60
|
//# sourceMappingURL=binary-uuid-column.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binary-uuid-column.js","sourceRoot":"","sources":["../../src/decorators/binary-uuid-column.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"binary-uuid-column.js","sourceRoot":"","sources":["../../src/decorators/binary-uuid-column.ts"],"names":[],"mappings":";;;AA0BA,4CA8BC;AAxDD,mCAAmD;AACnD,qCAAiE;AACjE,+BAAyC;AAEzC,0EAAmE;AAsBnE,SAAgB,gBAAgB,CAAC,OAA2B;IACxD,MA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IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IACtC,CAAC;IAED,IAAI,CAAC,KAAqB;QACtB,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;YAChB,OAAO,IAAI,CAAA;QACf,CAAC;QAED,MAAM,GAAG,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;QAEjC,OAAO,UAAU,CAAC,GAAG,CAAC,CAAA;IAC1B,CAAC;CACJ,CAAA;AAED,SAAS,UAAU,CAAC,GAAW;IAC3B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AACjH,CAAC"}
|
|
@@ -5,8 +5,9 @@ export declare abstract class AbstractOrmEntity {
|
|
|
5
5
|
setRepository(repository: Repository<this>): void;
|
|
6
6
|
setEntityManager(entityManager: EntityManager): void;
|
|
7
7
|
save(): Promise<this>;
|
|
8
|
-
protected fillable():
|
|
9
|
-
apply(fields: Record<string,
|
|
8
|
+
protected fillable(): (keyof this)[];
|
|
9
|
+
apply(fields: Record<string, unknown>): void;
|
|
10
10
|
private get repositoryOrEntityManager();
|
|
11
11
|
private get contextEntityManager();
|
|
12
|
+
protected generateBinaryUuidColumns(): void;
|
|
12
13
|
}
|
|
@@ -13,18 +13,22 @@ exports.AbstractOrmEntity = void 0;
|
|
|
13
13
|
const class_transformer_1 = require("class-transformer");
|
|
14
14
|
const typeorm_1 = require("typeorm");
|
|
15
15
|
const transaction_context_1 = require("../lib/transaction-context");
|
|
16
|
+
const generated_column_util_1 = require("../utils/generated-column.util");
|
|
17
|
+
// Blocked unconditionally in apply(), regardless of fillable(), to prevent prototype pollution
|
|
18
|
+
// if a fillable() override ever lists one of these by mistake.
|
|
19
|
+
const UNSAFE_APPLY_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
16
20
|
class AbstractOrmEntity {
|
|
17
21
|
repository;
|
|
18
22
|
entityManager;
|
|
19
23
|
setRepository(repository) {
|
|
20
|
-
if (this.repository
|
|
21
|
-
throw new Error('Cannot reassign Repository
|
|
24
|
+
if (this.repository) {
|
|
25
|
+
throw new Error('Cannot reassign Repository');
|
|
22
26
|
}
|
|
23
27
|
this.repository = repository;
|
|
24
28
|
}
|
|
25
29
|
setEntityManager(entityManager) {
|
|
26
|
-
if (this.
|
|
27
|
-
throw new Error('Cannot reassign
|
|
30
|
+
if (this.entityManager) {
|
|
31
|
+
throw new Error('Cannot reassign EntityManager');
|
|
28
32
|
}
|
|
29
33
|
this.entityManager = entityManager;
|
|
30
34
|
}
|
|
@@ -37,7 +41,7 @@ class AbstractOrmEntity {
|
|
|
37
41
|
apply(fields) {
|
|
38
42
|
const fillable = this.fillable();
|
|
39
43
|
Object.getOwnPropertyNames(fields)
|
|
40
|
-
.filter((f) => fillable.includes(f))
|
|
44
|
+
.filter((f) => !UNSAFE_APPLY_KEYS.has(f) && fillable.includes(f))
|
|
41
45
|
.forEach((f) => {
|
|
42
46
|
const v = fields[f];
|
|
43
47
|
if (v !== undefined) {
|
|
@@ -60,7 +64,37 @@ class AbstractOrmEntity {
|
|
|
60
64
|
}
|
|
61
65
|
get contextEntityManager() {
|
|
62
66
|
const store = transaction_context_1.txStorage.getStore();
|
|
63
|
-
|
|
67
|
+
if (!store) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
if (this.repository) {
|
|
71
|
+
return store.get(this.repository.manager.connection);
|
|
72
|
+
}
|
|
73
|
+
// No pinned repository to key the lookup by — e.g. a plain `new Entity()` never
|
|
74
|
+
// routed through AbstractOrmService, or one loaded via a raw EntityManager/Repository
|
|
75
|
+
// call. This entity has no way to know which DataSource it belongs to. Falling back to
|
|
76
|
+
// the sole active manager is provably correct when there's only one (a single-DataSource
|
|
77
|
+
// app can never have more than one entry here). With several active at once there's no
|
|
78
|
+
// way to tell which is right — fail loudly here instead of silently returning undefined,
|
|
79
|
+
// which would otherwise surface later as the unrelated-looking "No repository or entity
|
|
80
|
+
// manager available", hiding that this was actually an unresolvable ambiguity.
|
|
81
|
+
if (store.size > 1) {
|
|
82
|
+
throw new Error('Cannot determine ambient transaction manager: multiple DataSources are active and no repository is pinned to disambiguate');
|
|
83
|
+
}
|
|
84
|
+
return store.values().next().value;
|
|
85
|
+
}
|
|
86
|
+
generateBinaryUuidColumns() {
|
|
87
|
+
const generatedColumns = (0, generated_column_util_1.getGeneratedColumns)(this.constructor);
|
|
88
|
+
for (const column of generatedColumns) {
|
|
89
|
+
if (!column.generator) {
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const currentValue = this[column.propertyKey];
|
|
93
|
+
if (currentValue === null || currentValue === undefined) {
|
|
94
|
+
;
|
|
95
|
+
this[column.propertyKey] = column.generator();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
64
98
|
}
|
|
65
99
|
}
|
|
66
100
|
exports.AbstractOrmEntity = AbstractOrmEntity;
|
|
@@ -72,4 +106,10 @@ __decorate([
|
|
|
72
106
|
(0, class_transformer_1.Exclude)(),
|
|
73
107
|
__metadata("design:type", typeorm_1.EntityManager)
|
|
74
108
|
], AbstractOrmEntity.prototype, "entityManager", void 0);
|
|
109
|
+
__decorate([
|
|
110
|
+
(0, typeorm_1.BeforeInsert)(),
|
|
111
|
+
__metadata("design:type", Function),
|
|
112
|
+
__metadata("design:paramtypes", []),
|
|
113
|
+
__metadata("design:returntype", void 0)
|
|
114
|
+
], AbstractOrmEntity.prototype, "generateBinaryUuidColumns", null);
|
|
75
115
|
//# sourceMappingURL=abstract-orm.entity.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract-orm.entity.js","sourceRoot":"","sources":["../../src/entities/abstract-orm.entity.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yDAA2C;AAC3C,
|
|
1
|
+
{"version":3,"file":"abstract-orm.entity.js","sourceRoot":"","sources":["../../src/entities/abstract-orm.entity.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yDAA2C;AAC3C,qCAAiE;AAEjE,oEAAsD;AACtD,0EAAoE;AAEpE,+FAA+F;AAC/F,+DAA+D;AAC/D,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAA;AAE5E,MAAsB,iBAAiB;IAE3B,UAAU,CAAmB;IAE7B,aAAa,CAAgB;IAE9B,aAAa,CAAC,UAA4B;QAC7C,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAA;QACjD,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;IAChC,CAAC;IAEM,gBAAgB,CAAC,aAA4B;QAChD,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;QACpD,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACtC,CAAC;IAEM,IAAI;QACP,OAAO,IAAI,CAAC,yBAAyB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACpD,CAAC;IAES,QAAQ;QACd,OAAO,EAAE,CAAA;IACb,CAAC;IAEM,KAAK,CAAC,MAA+B;QACxC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAc,CAAA;QAE5C,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC;aAC7B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,CAAC,C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AyB;QAC/B,MAAM,gBAAgB,GAAG,IAAA,2CAAmB,EAAC,IAAI,CAAC,WAA0B,CAAC,CAAA;QAE7E,KAAK,MAAM,MAAM,IAAI,gBAAgB,EAAE,CAAC;YACpC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBACpB,SAAQ;YACZ,CAAC;YACD,MAAM,YAAY,GAAI,IAAgC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;YAC1E,IAAI,YAAY,KAAK,IAAI,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;gBACtD,CAAC;gBAAC,IAAgC,CAAC,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,SAAS,EAAE,CAAA;YAC/E,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AA5FD,8CA4FC;AA1FW;IADP,IAAA,2BAAO,GAAE;8BACW,oBAAU;qDAAM;AAE7B;IADP,IAAA,2BAAO,GAAE;8BACc,uBAAa;wDAAA;AA2E3B;IADT,IAAA,sBAAY,GAAE;;;;kEAad"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { BinaryUuidColumn } from './decorators/binary-uuid-column';
|
|
1
|
+
export { BinaryUuidColumn, BinaryUuidOptions, BinaryUuidVersion, binaryUuidTransformer, } from './decorators/binary-uuid-column';
|
|
2
2
|
export { AbstractOrmEntity } from './entities/abstract-orm.entity';
|
|
3
|
-
export { AbstractOrmService } from './services/abstract-orm.service';
|
|
3
|
+
export { AbstractOrmService, IOrmService } from './services/abstract-orm.service';
|
|
4
4
|
export { TransactionService } from './services/transaction.service';
|
|
5
5
|
export { OrmModule } from './orm.module';
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.OrmModule = exports.TransactionService = exports.AbstractOrmService = exports.AbstractOrmEntity = exports.BinaryUuidColumn = void 0;
|
|
3
|
+
exports.OrmModule = 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
|
+
Object.defineProperty(exports, "binaryUuidTransformer", { enumerable: true, get: function () { return binary_uuid_column_1.binaryUuidTransformer; } });
|
|
6
7
|
var abstract_orm_entity_1 = require("./entities/abstract-orm.entity");
|
|
7
8
|
Object.defineProperty(exports, "AbstractOrmEntity", { enumerable: true, get: function () { return abstract_orm_entity_1.AbstractOrmEntity; } });
|
|
8
9
|
var abstract_orm_service_1 = require("./services/abstract-orm.service");
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,
|
|
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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type Constructor<I = unknown> = new (...args: any[]) => I;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constructor.js","sourceRoot":"","sources":["../../src/lib/constructor.ts"],"names":[],"mappings":""}
|
|
@@ -1,7 +1,3 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
import { EntityManager } from 'typeorm';
|
|
3
|
-
|
|
4
|
-
manager?: EntityManager;
|
|
5
|
-
};
|
|
6
|
-
export declare const txStorage: AsyncLocalStorage<Store>;
|
|
7
|
-
export {};
|
|
2
|
+
import { DataSource, EntityManager } from 'typeorm';
|
|
3
|
+
export declare const txStorage: AsyncLocalStorage<Map<DataSource, EntityManager>>;
|
|
@@ -2,5 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.txStorage = void 0;
|
|
4
4
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
5
|
+
// Keyed by DataSource so a multi-connection app can have more than one ambient transaction
|
|
6
|
+
// active at once (e.g. one DataSource's transaction nested inside another's) without one
|
|
7
|
+
// overwriting or being mistaken for the other's.
|
|
5
8
|
exports.txStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
6
9
|
//# sourceMappingURL=transaction-context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-context.js","sourceRoot":"","sources":["../../src/lib/transaction-context.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;
|
|
1
|
+
{"version":3,"file":"transaction-context.js","sourceRoot":"","sources":["../../src/lib/transaction-context.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAGpD,2FAA2F;AAC3F,yFAAyF;AACzF,iDAAiD;AACpC,QAAA,SAAS,GAAG,IAAI,oCAAiB,EAAkC,CAAA"}
|
|
@@ -2,6 +2,7 @@ import { DeepPartial, DeleteResult, EntityManager, FindManyOptions, FindOneOptio
|
|
|
2
2
|
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
|
|
3
3
|
import { Type } from '@nestjs/common';
|
|
4
4
|
import { AbstractOrmEntity } from '../entities/abstract-orm.entity';
|
|
5
|
+
import { Constructor } from '../lib/constructor';
|
|
5
6
|
export interface IOrmService<T extends AbstractOrmEntity> {
|
|
6
7
|
readonly repository: Repository<T>;
|
|
7
8
|
create(props: DeepPartial<T>, enforceEntityManager?: EntityManager): Promise<T>;
|
|
@@ -10,9 +11,7 @@ export interface IOrmService<T extends AbstractOrmEntity> {
|
|
|
10
11
|
findOne(conditions: FindOneOptions<T>, enforceEntityManager?: EntityManager): Promise<T | null>;
|
|
11
12
|
count(conditions: FindManyOptions<T>, enforceEntityManager?: EntityManager): Promise<number>;
|
|
12
13
|
update(criteria: FindOptionsWhere<T>, props: QueryDeepPartialEntity<T>, enforceEntityManager?: EntityManager): Promise<UpdateResult>;
|
|
13
|
-
remove(
|
|
14
|
+
remove(conditions: FindOptionsWhere<T>, enforceEntityManager?: EntityManager): Promise<DeleteResult>;
|
|
14
15
|
createQueryBuilder(alias: string, enforceEntityManager?: EntityManager): SelectQueryBuilder<T>;
|
|
15
16
|
}
|
|
16
|
-
type Constructor<I> = new (...args: any[]) => I;
|
|
17
17
|
export declare function AbstractOrmService<T extends AbstractOrmEntity>(entity: Constructor<T>): Type<IOrmService<T>>;
|
|
18
|
-
export {};
|