@nathapp/nestjs-data 3.3.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-data",
3
- "version": "3.3.0",
3
+ "version": "4.0.1",
4
4
  "description": "ORM-agnostic data access abstractions for NestJS",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -13,20 +13,23 @@
13
13
  },
14
14
  "author": "William Khoo",
15
15
  "license": "ISC",
16
+ "engines": {
17
+ "node": "^20.19.0 || >=22.12.0"
18
+ },
16
19
  "types": "dist/index.d.ts",
17
20
  "main": "dist/index.js",
18
21
  "dependencies": {
19
- "@nathapp/nestjs-common": "^3.3.0"
22
+ "@nathapp/nestjs-common": "^4.0.1"
20
23
  },
21
24
  "devDependencies": {
22
- "@golevelup/ts-jest": "^0.6.1",
25
+ "@golevelup/ts-jest": "^3.0.0",
23
26
  "@nathapp/eslint-config": "1.0.1",
24
27
  "@nathapp/typescript-config": "1.0.1",
25
28
  "eslint": "^8.57.0",
26
29
  "typescript": "^5"
27
30
  },
28
31
  "peerDependencies": {
29
- "@nathapp/nestjs-common": "^3.0.0",
30
- "@nestjs/common": "^10.0.0 || ^11.0.0"
32
+ "@nathapp/nestjs-common": "^4.0.0-rc.0",
33
+ "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0"
31
34
  }
32
35
  }
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@3.3.0 build
3
- > rimraf dist && tsc -p tsconfig.json
4
-
package/CHANGELOG.md DELETED
@@ -1,111 +0,0 @@
1
- # @nathapp/nestjs-data
2
-
3
- ## 3.3.0
4
-
5
- ### Patch Changes
6
-
7
- - @nathapp/nestjs-common@3.3.0
8
-
9
- ## 3.2.1
10
-
11
- ### Patch Changes
12
-
13
- - 0610b83: Fix Exception Bug on nestjs-common
14
- - Updated dependencies [0610b83]
15
- - @nathapp/nestjs-common@3.2.1
16
-
17
- ## 3.2.0
18
-
19
- ### Minor Changes
20
-
21
- - 1876b9a: ### nestjs-auth
22
-
23
- - Add JWKS support via `JwksJwtStrategyProvider` and `createJwksStrategyProvider` factory — enables remote key resolution through `jwks-rsa` (optional peer dep)
24
- - Add `validateJwksOptions` security guard and `JwksOptions` interface
25
- - Export `JwksJwtStrategyProvider` and `JwksOptions` from the public API
26
- - Fix permission guard and JWT module immutability issues from code review
27
-
28
- ### nestjs-typeorm
29
-
30
- - Add `AbstractTypeOrmRepository<TDomain, TEntity, TId>` — portable `IRepository` implementation decoupled from TypeORM internals
31
- - Add `TYPEORM_TRANSACTION_ALS` DI token and publish it from `forRoot`/`forRootAsync`
32
- - `forCustomRepository` now instantiates `AbstractTypeOrmRepository` subclasses with the correct per-DataSource tx manager token
33
- - Add `getTypeOrmTransactionManagerToken(name?)` helper for multi-DataSource wiring
34
- - Named DataSource tx tokens no longer collide; default DataSource still aliases the global `TRANSACTION_MANAGER` symbol
35
-
36
- ### nestjs-prisma
37
-
38
- - Add `getPrismaTransactionManagerToken(name?)` helper for multi-DataSource wiring
39
- - `forRoot` / `forRootAsync` register named tx manager token + default-only guard to prevent collision
40
-
41
- ### nestjs-data
42
-
43
- - Add `IRepository<TDomain, TId>` portable repository contract
44
- - Fix missing `@nathapp/nestjs-common` peer dep for turborepo build resolution
45
-
46
- ### nestjs-common
47
-
48
- - Add `request-ip` utility for extracting client IP across Express and Fastify adapters
49
-
50
- ### nestjs-cache
51
-
52
- - Fix cache interceptor, cache manager, and cache tag registry immutability and type issues
53
-
54
- ### nestjs-app
55
-
56
- - Fix `nathapp.ts` and `app-factory.ts` code review findings (immutability, error handling)
57
-
58
- ### nestjs-queue
59
-
60
- - Upgrade `uuid` dependency from `^9.0.0` to `^11.1.1` (security)
61
- - Fix BullMQ health check to use `IRedisClient.info()` (aligned with BullMQ interface)
62
-
63
- ### nestjs-notification
64
-
65
- - Upgrade `nodemailer` dev dep from `^7` to `^8` — resolves SMTP command injection CVEs (GHSA-c7w3-x93f-qmm8, GHSA-vvjj-xcjg-gr5g)
66
-
67
- ### nestjs-storage
68
-
69
- - Fix code review findings (immutability, validation)
70
-
71
- ### nestjs-throttler
72
-
73
- - Fix code review findings
74
-
75
- ### All packages
76
-
77
- - Upgrade AJV to v8 (removes root override that broke `@fastify/ajv-compiler`)
78
- - Align all package versions to 3.1.3 as baseline for this minor release
79
-
80
- ### Patch Changes
81
-
82
- - Updated dependencies [1876b9a]
83
- - @nathapp/nestjs-common@3.2.0
84
-
85
- ## 3.0.4
86
-
87
- ### Patch Changes
88
-
89
- - a48beb2: transaction manager symbol bug fix
90
-
91
- ## 3.0.3
92
-
93
- ### Patch Changes
94
-
95
- - cb97b64: fix typeorm and transactionManager issue
96
-
97
- ## 3.0.2
98
-
99
- ### Patch Changes
100
-
101
- - a448f5b: add irepository and abstract repository
102
-
103
- ## 3.0.1
104
-
105
- ### Patch Changes
106
-
107
- - Add ITransactionManager interface and ORM-specific implementations
108
-
109
- - **nestjs-data**: New package with `ITransactionManager` interface and `TRANSACTION_MANAGER` DI token for ORM-agnostic transaction management via AsyncLocalStorage
110
- - **nestjs-prisma**: Add `PrismaTransactionManager` implementing `ITransactionManager` with Prisma interactive transactions
111
- - **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
- }