@nathapp/nestjs-data 4.0.0 → 4.0.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-data",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
4
  "description": "ORM-agnostic data access abstractions for NestJS",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -19,10 +19,10 @@
19
19
  "types": "dist/index.d.ts",
20
20
  "main": "dist/index.js",
21
21
  "dependencies": {
22
- "@nathapp/nestjs-common": "^4.0.0"
22
+ "@nathapp/nestjs-common": "^4.0.2"
23
23
  },
24
24
  "devDependencies": {
25
- "@golevelup/ts-jest": "^0.6.1",
25
+ "@golevelup/ts-jest": "^3.0.0",
26
26
  "@nathapp/eslint-config": "1.0.1",
27
27
  "@nathapp/typescript-config": "1.0.1",
28
28
  "eslint": "^8.57.0",
package/.eslintrc.js DELETED
@@ -1,8 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- extends: ["@nathapp/eslint-config/library.js"],
4
- parser: "@typescript-eslint/parser",
5
- parserOptions: {
6
- project: true,
7
- },
8
- };
@@ -1,4 +0,0 @@
1
-
2
- > @nathapp/nestjs-data@4.0.0 build
3
- > rimraf dist && tsc -p tsconfig.json
4
-
package/CHANGELOG.md DELETED
@@ -1,144 +0,0 @@
1
- # @nathapp/nestjs-data
2
-
3
- ## 4.0.0
4
-
5
- ### Major Changes
6
-
7
- - 2319e9d: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
8
-
9
- Other consumer-facing changes:
10
-
11
- - `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
12
- - Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
13
-
14
- ### Patch Changes
15
-
16
- - Updated dependencies [668055b]
17
- - Updated dependencies [2319e9d]
18
- - @nathapp/nestjs-common@4.0.0
19
-
20
- ## 4.0.0-rc.0
21
-
22
- ### Major Changes
23
-
24
- - c3aeb46: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
25
-
26
- Other consumer-facing changes:
27
-
28
- - `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
29
- - Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
30
-
31
- ### Patch Changes
32
-
33
- - Updated dependencies [c3aeb46]
34
- - @nathapp/nestjs-common@4.0.0-rc.0
35
-
36
- ## 3.3.0
37
-
38
- ### Patch Changes
39
-
40
- - @nathapp/nestjs-common@3.3.0
41
-
42
- ## 3.2.1
43
-
44
- ### Patch Changes
45
-
46
- - 0610b83: Fix Exception Bug on nestjs-common
47
- - Updated dependencies [0610b83]
48
- - @nathapp/nestjs-common@3.2.1
49
-
50
- ## 3.2.0
51
-
52
- ### Minor Changes
53
-
54
- - 1876b9a: ### nestjs-auth
55
-
56
- - Add JWKS support via `JwksJwtStrategyProvider` and `createJwksStrategyProvider` factory — enables remote key resolution through `jwks-rsa` (optional peer dep)
57
- - Add `validateJwksOptions` security guard and `JwksOptions` interface
58
- - Export `JwksJwtStrategyProvider` and `JwksOptions` from the public API
59
- - Fix permission guard and JWT module immutability issues from code review
60
-
61
- ### nestjs-typeorm
62
-
63
- - Add `AbstractTypeOrmRepository<TDomain, TEntity, TId>` — portable `IRepository` implementation decoupled from TypeORM internals
64
- - Add `TYPEORM_TRANSACTION_ALS` DI token and publish it from `forRoot`/`forRootAsync`
65
- - `forCustomRepository` now instantiates `AbstractTypeOrmRepository` subclasses with the correct per-DataSource tx manager token
66
- - Add `getTypeOrmTransactionManagerToken(name?)` helper for multi-DataSource wiring
67
- - Named DataSource tx tokens no longer collide; default DataSource still aliases the global `TRANSACTION_MANAGER` symbol
68
-
69
- ### nestjs-prisma
70
-
71
- - Add `getPrismaTransactionManagerToken(name?)` helper for multi-DataSource wiring
72
- - `forRoot` / `forRootAsync` register named tx manager token + default-only guard to prevent collision
73
-
74
- ### nestjs-data
75
-
76
- - Add `IRepository<TDomain, TId>` portable repository contract
77
- - Fix missing `@nathapp/nestjs-common` peer dep for turborepo build resolution
78
-
79
- ### nestjs-common
80
-
81
- - Add `request-ip` utility for extracting client IP across Express and Fastify adapters
82
-
83
- ### nestjs-cache
84
-
85
- - Fix cache interceptor, cache manager, and cache tag registry immutability and type issues
86
-
87
- ### nestjs-app
88
-
89
- - Fix `nathapp.ts` and `app-factory.ts` code review findings (immutability, error handling)
90
-
91
- ### nestjs-queue
92
-
93
- - Upgrade `uuid` dependency from `^9.0.0` to `^11.1.1` (security)
94
- - Fix BullMQ health check to use `IRedisClient.info()` (aligned with BullMQ interface)
95
-
96
- ### nestjs-notification
97
-
98
- - Upgrade `nodemailer` dev dep from `^7` to `^8` — resolves SMTP command injection CVEs (GHSA-c7w3-x93f-qmm8, GHSA-vvjj-xcjg-gr5g)
99
-
100
- ### nestjs-storage
101
-
102
- - Fix code review findings (immutability, validation)
103
-
104
- ### nestjs-throttler
105
-
106
- - Fix code review findings
107
-
108
- ### All packages
109
-
110
- - Upgrade AJV to v8 (removes root override that broke `@fastify/ajv-compiler`)
111
- - Align all package versions to 3.1.3 as baseline for this minor release
112
-
113
- ### Patch Changes
114
-
115
- - Updated dependencies [1876b9a]
116
- - @nathapp/nestjs-common@3.2.0
117
-
118
- ## 3.0.4
119
-
120
- ### Patch Changes
121
-
122
- - a48beb2: transaction manager symbol bug fix
123
-
124
- ## 3.0.3
125
-
126
- ### Patch Changes
127
-
128
- - cb97b64: fix typeorm and transactionManager issue
129
-
130
- ## 3.0.2
131
-
132
- ### Patch Changes
133
-
134
- - a448f5b: add irepository and abstract repository
135
-
136
- ## 3.0.1
137
-
138
- ### Patch Changes
139
-
140
- - Add ITransactionManager interface and ORM-specific implementations
141
-
142
- - **nestjs-data**: New package with `ITransactionManager` interface and `TRANSACTION_MANAGER` DI token for ORM-agnostic transaction management via AsyncLocalStorage
143
- - **nestjs-prisma**: Add `PrismaTransactionManager` implementing `ITransactionManager` with Prisma interactive transactions
144
- - **nestjs-typeorm**: Add `TypeOrmTransactionManager` implementing `ITransactionManager` with TypeORM QueryRunner transactions
@@ -1 +0,0 @@
1
- export * from './tokens';
@@ -1,33 +0,0 @@
1
- /**
2
- * Global DI token for ITransactionManager.
3
- *
4
- * Uses Symbol.for (not Symbol) so the token is identical across all
5
- * JavaScript realms, bundles, and duplicate package installations.
6
- * This prevents UnknownDependenciesException when the consuming app
7
- * and @nathapp/nestjs-prisma / @nathapp/nestjs-typeorm resolve
8
- * @nathapp/nestjs-data from different node_modules paths or bundles.
9
- *
10
- * --------------------------------------------------------------------------
11
- * IMPORTANT — Single-DB vs Multi-DB usage
12
- * --------------------------------------------------------------------------
13
- *
14
- * **Single-DB apps (recommended):**
15
- * @Inject(TRANSACTION_MANAGER) private readonly tx: ITransactionManager
16
- *
17
- * This works because the default connection registers TRANSACTION_MANAGER
18
- * as an alias to the default transaction manager automatically.
19
- *
20
- * **Multi-DB apps (MUST use named tokens):**
21
- * // CORRECT — explicit per-connection token
22
- * @Inject(getPrismaTransactionManagerToken('dbA')) private readonly txA: ITransactionManager
23
- * @Inject(getTypeOrmTransactionManagerToken('analytics')) private readonly txAnalytics: ITransactionManager
24
- *
25
- * // WRONG — TRANSACTION_MANAGER is only an alias for the DEFAULT connection.
26
- * // Named connections do NOT register this global token.
27
- * @Inject(TRANSACTION_MANAGER) private readonly tx: ITransactionManager // ❌ only resolves default!
28
- *
29
- * If you inject TRANSACTION_MANAGER in a multi-DB app, you silently get the
30
- * default connection's tx manager. Writes to other databases will NOT be
31
- * covered by the transaction. Use named tokens for every non-default connection.
32
- */
33
- export const TRANSACTION_MANAGER = Symbol.for('TRANSACTION_MANAGER');
package/lib/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './constant';
2
- export * from './interface';
@@ -1,2 +0,0 @@
1
- export * from './transaction-manager.interface';
2
- export * from './repository.interface';
@@ -1,87 +0,0 @@
1
- import type { IPageOption } from '@nathapp/nestjs-common';
2
-
3
- /**
4
- * ORM-agnostic page result shape returned by `IRepository.findAll`.
5
- *
6
- * Mirrors the shape of `Page<T>` from `@nathapp/nestjs-common` but is declared
7
- * structurally here so `nestjs-data` does not need a runtime dependency on
8
- * `nestjs-common`. Concrete ORM base classes return the real `Page<T>` instance.
9
- */
10
- export interface IPageResult<T> {
11
- total: number;
12
- current: number;
13
- size: number;
14
- hasNext: boolean;
15
- hasPrev: boolean;
16
- records: T[];
17
- }
18
-
19
- /**
20
- * Portable repository contract.
21
- *
22
- * Services depend on `IRepository<TDomain>` via a DI token (e.g. `USER_REPOSITORY`)
23
- * so business logic stays decoupled from the underlying ORM. Concrete
24
- * implementations live in `@nathapp/nestjs-typeorm` (`AbstractTypeOrmRepository`)
25
- * and `@nathapp/nestjs-prisma` (`AbstractPrismaRepository`).
26
- *
27
- * For ORM-specific power (Prisma `include`, TypeORM `QueryBuilder`, raw SQL,
28
- * stored procedures), inject the concrete repo class directly — those call sites
29
- * intentionally lose portability.
30
- *
31
- * @typeParam TDomain - Domain model type (a plain interface or class owned by
32
- * the service layer). Never an ORM-generated type.
33
- * @typeParam TId - Primary key type. Defaults to string.
34
- *
35
- * @remarks
36
- * Concrete base classes (`AbstractTypeOrmRepository`, `AbstractPrismaRepository`)
37
- * structurally assume the primary key column/property is named `"id"`. If your
38
- * schema uses a different name (e.g. `userId`, `uuid`), you must bypass the
39
- * abstract base and implement `IRepository` directly, or use an ORM-specific
40
- * escape hatch.
41
- */
42
- export interface IRepository<TDomain, TId = string> {
43
- /**
44
- * Find a single entity by primary key.
45
- * Returns `null` if not found (does NOT throw).
46
- */
47
- findById(id: TId): Promise<TDomain | null>;
48
-
49
- /**
50
- * Find a single entity matching all fields in `criteria` (equality only).
51
- * For complex queries, use the concrete ORM repo's escape hatches.
52
- */
53
- findOne(criteria: Partial<TDomain>): Promise<TDomain | null>;
54
-
55
- /**
56
- * Paginated list of entities. `page.current` is 1-indexed, `page.size` is items
57
- * per page. Returns total count and pagination metadata in `IPageResult`.
58
- *
59
- * @remarks Filtering criteria are NOT supported here — use the concrete ORM
60
- * repo's escape hatches for filtered list queries.
61
- */
62
- findAll(page: IPageOption): Promise<IPageResult<TDomain>>;
63
-
64
- /**
65
- * Count entities. Without criteria, returns total. With criteria, counts
66
- * matching entities (equality only).
67
- */
68
- count(criteria?: Partial<TDomain>): Promise<number>;
69
-
70
- /**
71
- * Create a new entity. Returns the persisted entity (with any DB-generated
72
- * fields populated, e.g. autoincrement id, createdAt).
73
- */
74
- create(input: TDomain): Promise<TDomain>;
75
-
76
- /**
77
- * Apply a partial patch to an existing entity. Returns the updated entity.
78
- * Throws if the entity does not exist.
79
- */
80
- update(id: TId, patch: Partial<TDomain>): Promise<TDomain>;
81
-
82
- /**
83
- * Delete an entity by primary key. Idempotent — no-op if entity does not exist
84
- * (concrete impls may differ; document any deviation).
85
- */
86
- delete(id: TId): Promise<void>;
87
- }
@@ -1,40 +0,0 @@
1
- /**
2
- * ORM-agnostic transaction manager using AsyncLocalStorage.
3
- *
4
- * Implementations:
5
- * - PrismaTransactionManager (@nathapp/nestjs-prisma)
6
- * - TypeOrmTransactionManager (@nathapp/nestjs-typeorm)
7
- *
8
- * Usage:
9
- * ```typescript
10
- * @Inject(TRANSACTION_MANAGER)
11
- * private readonly txManager: ITransactionManager;
12
- *
13
- * async register(input: CreateAccountInput) {
14
- * return this.txManager.run(() => {
15
- * const account = await this.accountService.create(input);
16
- * await this.membershipService.assignRoles(account.id, roles);
17
- * return account;
18
- * });
19
- * }
20
- * ```
21
- */
22
- export interface ITransactionManager {
23
- /**
24
- * Execute fn within a transaction.
25
- * Auto-commits on success, rolls back on error.
26
- * Supports nesting (inner calls reuse the outer transaction).
27
- */
28
- run<T>(fn: () => Promise<T>): Promise<T>;
29
-
30
- /**
31
- * Get the active transaction client, or the root client if not in a transaction.
32
- * Repositories call this instead of using their injected client directly.
33
- */
34
- getClient<C = unknown>(): C;
35
-
36
- /**
37
- * Check if currently inside a transaction.
38
- */
39
- isInTransaction(): boolean;
40
- }
@@ -1,27 +0,0 @@
1
- {
2
- "moduleFileExtensions": ["js", "json", "ts", "d.ts"],
3
- "rootDir": "../",
4
- "testEnvironment": "node",
5
- "testMatch": ["**/.nax/**/*.test.ts"],
6
- "transform": {
7
- "^.+\\.(t)s$": [
8
- "ts-jest",
9
- {
10
- "diagnostics": true,
11
- "tsconfig": {
12
- "esModuleInterop": true,
13
- "emitDecoratorMetadata": true,
14
- "experimentalDecorators": true
15
- }
16
- }
17
- ]
18
- },
19
- "collectCoverageFrom": [
20
- "lib/**/*.ts",
21
- "!lib/**/*.spec.ts",
22
- "!lib/**/*.d.ts",
23
- "!**/node_modules/**"
24
- ],
25
- "forceExit": true,
26
- "maxWorkers": 1
27
- }
@@ -1,25 +0,0 @@
1
- {
2
- "moduleFileExtensions": [
3
- "js",
4
- "json",
5
- "ts",
6
- "d.ts"
7
- ],
8
- "rootDir": "../",
9
- "testEnvironment": "node",
10
- "testRegex": ".spec.ts$",
11
- "transform": {
12
- "^.+\\.(t)s$": [
13
- "ts-jest",
14
- {
15
- "diagnostics": true,
16
- "isolatedModules": true
17
- }
18
- ]
19
- },
20
- "collectCoverageFrom": [
21
- "lib/**/*.ts",
22
- "!**/node_modules/**"
23
- ],
24
- "coverageProvider": "v8"
25
- }
@@ -1,112 +0,0 @@
1
- import { IRepository } from '../lib/interface/repository.interface';
2
-
3
- interface User {
4
- id: string;
5
- email: string;
6
- name: string;
7
- }
8
-
9
- class InMemoryUserRepository implements IRepository<User, string> {
10
- private store = new Map<string, User>();
11
-
12
- async findById(id: string): Promise<User | null> {
13
- return this.store.get(id) ?? null;
14
- }
15
-
16
- async findOne(criteria: Partial<User>): Promise<User | null> {
17
- for (const user of this.store.values()) {
18
- if (Object.entries(criteria).every(([k, v]) => (user as any)[k] === v)) {
19
- return user;
20
- }
21
- }
22
- return null;
23
- }
24
-
25
- async findAll(page: { current: number; size: number }) {
26
- const records = Array.from(this.store.values());
27
- return {
28
- total: records.length,
29
- current: page.current,
30
- size: page.size,
31
- hasNext: false,
32
- hasPrev: false,
33
- records,
34
- };
35
- }
36
-
37
- async count(criteria?: Partial<User>): Promise<number> {
38
- if (!criteria) return this.store.size;
39
- let n = 0;
40
- for (const user of this.store.values()) {
41
- if (Object.entries(criteria).every(([k, v]) => (user as any)[k] === v)) n++;
42
- }
43
- return n;
44
- }
45
-
46
- async create(input: User): Promise<User> {
47
- this.store.set(input.id, input);
48
- return input;
49
- }
50
-
51
- async update(id: string, patch: Partial<User>): Promise<User> {
52
- const existing = this.store.get(id);
53
- if (!existing) throw new Error('not found');
54
- const updated = { ...existing, ...patch };
55
- this.store.set(id, updated);
56
- return updated;
57
- }
58
-
59
- async delete(id: string): Promise<void> {
60
- this.store.delete(id);
61
- }
62
- }
63
-
64
- describe('IRepository contract', () => {
65
- let repo: IRepository<User, string>;
66
-
67
- beforeEach(() => {
68
- repo = new InMemoryUserRepository();
69
- });
70
-
71
- it('create + findById round-trips a domain entity', async () => {
72
- const user: User = { id: '1', email: 'a@b.c', name: 'Alice' };
73
- await repo.create(user);
74
- expect(await repo.findById('1')).toEqual(user);
75
- });
76
-
77
- it('findById returns null for missing entity', async () => {
78
- expect(await repo.findById('missing')).toBeNull();
79
- });
80
-
81
- it('findOne matches by partial criteria', async () => {
82
- await repo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
83
- await repo.create({ id: '2', email: 'b@b.c', name: 'Bob' });
84
- expect(await repo.findOne({ name: 'Bob' })).toMatchObject({ id: '2' });
85
- });
86
-
87
- it('findAll returns Page-shaped result', async () => {
88
- await repo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
89
- const page = await repo.findAll({ current: 1, size: 10 });
90
- expect(page.total).toBe(1);
91
- expect(page.records).toHaveLength(1);
92
- });
93
-
94
- it('count without criteria returns total', async () => {
95
- await repo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
96
- await repo.create({ id: '2', email: 'b@b.c', name: 'Bob' });
97
- expect(await repo.count()).toBe(2);
98
- expect(await repo.count({ name: 'Alice' })).toBe(1);
99
- });
100
-
101
- it('update merges patch into existing entity', async () => {
102
- await repo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
103
- const updated = await repo.update('1', { name: 'Alicia' });
104
- expect(updated).toMatchObject({ id: '1', name: 'Alicia', email: 'a@b.c' });
105
- });
106
-
107
- it('delete removes the entity', async () => {
108
- await repo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
109
- await repo.delete('1');
110
- expect(await repo.findById('1')).toBeNull();
111
- });
112
- });
@@ -1,11 +0,0 @@
1
- import { TRANSACTION_MANAGER } from '../lib/constant/tokens';
2
-
3
- describe('TRANSACTION_MANAGER token', () => {
4
- it('should be a Symbol', () => {
5
- expect(typeof TRANSACTION_MANAGER).toBe('symbol');
6
- });
7
-
8
- it('should have the correct description', () => {
9
- expect(TRANSACTION_MANAGER.toString()).toBe('Symbol(TRANSACTION_MANAGER)');
10
- });
11
- });
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "@nathapp/typescript-config/base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./lib",
6
- },
7
- "include": ["lib/**/*"],
8
- "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
9
- }