@nathapp/nestjs-data 3.0.1 → 3.0.3

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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @nathapp/nestjs-data@3.0.1 build
2
+ > @nathapp/nestjs-data@3.0.3 build
3
3
  > rimraf dist && tsc -p tsconfig.json
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @nathapp/nestjs-data
2
2
 
3
+ ## 3.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - cb97b64: fix typeorm and transactionManager issue
8
+
9
+ ## 3.0.2
10
+
11
+ ### Patch Changes
12
+
13
+ - a448f5b: add irepository and abstract repository
14
+
3
15
  ## 3.0.1
4
16
 
5
17
  ### Patch Changes
package/CLAUDE.md ADDED
@@ -0,0 +1,42 @@
1
+ # @nathapp/nestjs-data
2
+
3
+ ORM-agnostic data access abstractions. Pure-type package — no NestJS or ORM imports.
4
+
5
+ ## Exports
6
+
7
+ - `TRANSACTION_MANAGER` (Symbol) — DI token for `ITransactionManager`
8
+ - `ITransactionManager` — orm-agnostic transaction control via AsyncLocalStorage
9
+ - `IRepository<TDomain, TId>` — portable repository contract (CRUD + pagination)
10
+ - `IPageResult<T>` — structural shape of paginated results (compatible with `Page<T>` from `@nathapp/nestjs-common`)
11
+
12
+ ## Design
13
+
14
+ Services depend on `IRepository<TDomain>` via DI tokens (e.g. `USER_REPOSITORY`),
15
+ never on the concrete ORM repo class. Concrete implementations live in
16
+ `@nathapp/nestjs-typeorm` (`AbstractTypeOrmRepository`) and `@nathapp/nestjs-prisma`
17
+ (`AbstractPrismaRepository`). Both implementations:
18
+
19
+ - Accept the `TRANSACTION_MANAGER` provider and resolve the active client per operation.
20
+ - Require subclasses to implement three mappers (`toDomain`, `toPersistenceCreate`, `toPersistenceUpdate`).
21
+ - Return `Page<T>` from `@nathapp/nestjs-common` for `findAll` (compatible with `IPageResult<T>`).
22
+
23
+ For ORM-specific power (Prisma `include`, TypeORM `QueryBuilder`, raw SQL,
24
+ stored procedures), inject the concrete repo class directly — those call sites
25
+ intentionally lose portability. The portable surface is the `IRepository`
26
+ contract; everything else is an escape hatch.
27
+
28
+ ## Build
29
+
30
+ ```bash
31
+ cd packages/nestjs-data && npm run build
32
+ ```
33
+
34
+ ## Peer Dependencies
35
+
36
+ - `@nestjs/common` — for `Inject` typing
37
+ - `@nathapp/nestjs-common` — for `IPageOption` (used by `IRepository.findAll`)
38
+
39
+ ## Limitations
40
+
41
+ - Concrete base classes assume the primary key column/property is named `"id"`.
42
+ Schemas with different PK names must implement `IRepository` directly.
@@ -1 +1,2 @@
1
1
  export * from './transaction-manager.interface';
2
+ export * from './repository.interface';
@@ -15,4 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./transaction-manager.interface"), exports);
18
+ __exportStar(require("./repository.interface"), exports);
18
19
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/interface/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kEAAgD"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/interface/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kEAAgD;AAChD,yDAAuC"}
@@ -0,0 +1,18 @@
1
+ import type { IPageOption } from '@nathapp/nestjs-common';
2
+ export interface IPageResult<T> {
3
+ total: number;
4
+ current: number;
5
+ size: number;
6
+ hasNext: boolean;
7
+ hasPrev: boolean;
8
+ records: T[];
9
+ }
10
+ export interface IRepository<TDomain, TId = string> {
11
+ findById(id: TId): Promise<TDomain | null>;
12
+ findOne(criteria: Partial<TDomain>): Promise<TDomain | null>;
13
+ findAll(page: IPageOption): Promise<IPageResult<TDomain>>;
14
+ count(criteria?: Partial<TDomain>): Promise<number>;
15
+ create(input: TDomain): Promise<TDomain>;
16
+ update(id: TId, patch: Partial<TDomain>): Promise<TDomain>;
17
+ delete(id: TId): Promise<void>;
18
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=repository.interface.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repository.interface.js","sourceRoot":"","sources":["../../lib/interface/repository.interface.ts"],"names":[],"mappings":""}
@@ -1 +1,2 @@
1
1
  export * from './transaction-manager.interface';
2
+ export * from './repository.interface';
@@ -0,0 +1,87 @@
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-data",
3
- "version": "3.0.1",
3
+ "version": "3.0.3",
4
4
  "description": "ORM-agnostic data access abstractions for NestJS",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -12,7 +12,9 @@
12
12
  "license": "ISC",
13
13
  "types": "dist/index.d.ts",
14
14
  "main": "dist/index.js",
15
- "dependencies": {},
15
+ "dependencies": {
16
+ "@nathapp/nestjs-common": "^3.0.0"
17
+ },
16
18
  "devDependencies": {
17
19
  "@nathapp/eslint-config": "1.0.1",
18
20
  "@nathapp/typescript-config": "1.0.1",
@@ -21,6 +23,7 @@
21
23
  "typescript": "^5"
22
24
  },
23
25
  "peerDependencies": {
24
- "@nestjs/common": "^10.0.0 || ^11.0.0"
26
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
27
+ "@nathapp/nestjs-common": "^3.0.0"
25
28
  }
26
29
  }
@@ -0,0 +1,112 @@
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
+ });