@nathapp/nestjs-prisma 3.0.1 → 3.1.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.
Files changed (37) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +28 -0
  3. package/CLAUDE.md +35 -0
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +1 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/prisma.interfaces.d.ts +1 -0
  8. package/dist/prisma.module.js +60 -4
  9. package/dist/prisma.module.js.map +1 -1
  10. package/dist/repository/abstract-prisma.repository.d.ts +51 -0
  11. package/dist/repository/abstract-prisma.repository.js +69 -0
  12. package/dist/repository/abstract-prisma.repository.js.map +1 -0
  13. package/dist/repository/index.d.ts +1 -0
  14. package/dist/repository/index.js +18 -0
  15. package/dist/repository/index.js.map +1 -0
  16. package/dist/transaction/index.d.ts +1 -0
  17. package/dist/transaction/index.js +1 -0
  18. package/dist/transaction/index.js.map +1 -1
  19. package/dist/transaction/prisma-transaction-manager.d.ts +2 -1
  20. package/dist/transaction/prisma-transaction-manager.js +6 -3
  21. package/dist/transaction/prisma-transaction-manager.js.map +1 -1
  22. package/dist/transaction/prisma-transaction.constants.d.ts +2 -0
  23. package/dist/transaction/prisma-transaction.constants.js +9 -0
  24. package/dist/transaction/prisma-transaction.constants.js.map +1 -0
  25. package/lib/index.ts +1 -0
  26. package/lib/prisma.interfaces.ts +9 -0
  27. package/lib/prisma.module.ts +76 -6
  28. package/lib/repository/abstract-prisma.repository.ts +120 -0
  29. package/lib/repository/index.ts +1 -0
  30. package/lib/transaction/index.ts +1 -0
  31. package/lib/transaction/prisma-transaction-manager.ts +10 -3
  32. package/lib/transaction/prisma-transaction.constants.ts +13 -0
  33. package/package.json +2 -2
  34. package/test/jest-test.json +4 -0
  35. package/test/repository/abstract-prisma.repository.spec.ts +157 -0
  36. package/test/transparent-transaction.spec.ts +332 -0
  37. package/.turbo/turbo-test.log +0 -43
@@ -0,0 +1,120 @@
1
+ import { Inject } from '@nestjs/common';
2
+ import {
3
+ IPageResult,
4
+ IRepository,
5
+ ITransactionManager,
6
+ TRANSACTION_MANAGER,
7
+ } from '@nathapp/nestjs-data';
8
+ import { Page, resolvePageOption } from '@nathapp/nestjs-common';
9
+ import type { IPageOption } from '@nathapp/nestjs-common';
10
+ import { PrismaClientLike } from '../prisma.interfaces';
11
+
12
+ /**
13
+ * Generic shape of a Prisma model delegate (e.g. `prisma.user`).
14
+ * We type structurally to avoid coupling to consumer-generated Prisma types.
15
+ */
16
+ export interface PrismaModelDelegate<TModel, TId> {
17
+ findUnique(args: { where: { id: TId } }): Promise<TModel | null>;
18
+ findFirst(args: { where: any }): Promise<TModel | null>;
19
+ findMany(args: { skip: number; take: number; where?: any }): Promise<TModel[]>;
20
+ count(args: { where?: any }): Promise<number>;
21
+ create(args: { data: any }): Promise<TModel>;
22
+ update(args: { where: { id: TId }; data: any }): Promise<TModel>;
23
+ delete(args: { where: { id: TId } }): Promise<TModel>;
24
+ }
25
+
26
+ /**
27
+ * Abstract Prisma implementation of `IRepository<TDomain, TId>`.
28
+ *
29
+ * Subclasses MUST implement four hooks:
30
+ * - `modelDelegate(client)` — returns the Prisma model delegate (e.g. `client.user`)
31
+ * - `toDomain(model)` — persistence → domain
32
+ * - `toPersistenceCreate(domain)` — domain → Prisma create input
33
+ * - `toPersistenceUpdate(partial)` — partial domain → Prisma update input
34
+ *
35
+ * Note on transactions: PrismaModule's transparent proxy already routes
36
+ * `prismaService.client.user.x()` to the active transaction client. This base
37
+ * class still calls `tx.getClient()` per operation for explicit decoupling and
38
+ * to make services portable across ORMs via the `IRepository` contract.
39
+ *
40
+ * Limitation: This class assumes a single Prisma database (the one bound to
41
+ * the `TRANSACTION_MANAGER` token). Multi-DB Prisma setups currently expose
42
+ * only one tx manager; per-DB tx managers are a future enhancement.
43
+ *
44
+ * Example:
45
+ * ```typescript
46
+ * @Injectable()
47
+ * export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
48
+ * constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
49
+ * protected modelDelegate(client: any) { return client.user; }
50
+ * protected toDomain(m: UserModel): User { return { id: m.id, email: m.emailAddress, name: m.fullName }; }
51
+ * protected toPersistenceCreate(d: User) { return { id: d.id, emailAddress: d.email, fullName: d.name }; }
52
+ * protected toPersistenceUpdate(p: Partial<User>) {
53
+ * const out: any = {};
54
+ * if (p.email !== undefined) out.emailAddress = p.email;
55
+ * if (p.name !== undefined) out.fullName = p.name;
56
+ * return out;
57
+ * }
58
+ * }
59
+ * ```
60
+ */
61
+ export abstract class AbstractPrismaRepository<TDomain, TModel, TId = string>
62
+ implements IRepository<TDomain, TId> {
63
+ constructor(@Inject(TRANSACTION_MANAGER) protected readonly tx: ITransactionManager) {}
64
+
65
+ protected abstract modelDelegate(client: PrismaClientLike): PrismaModelDelegate<TModel, TId>;
66
+ protected abstract toDomain(model: TModel): TDomain;
67
+ protected abstract toPersistenceCreate(domain: TDomain): any;
68
+ protected abstract toPersistenceUpdate(patch: Partial<TDomain>): any;
69
+
70
+ /**
71
+ * CRITICAL: getter, not field. Resolved per operation so AsyncLocalStorage-based
72
+ * transaction propagation works. Do NOT cache.
73
+ */
74
+ protected get model(): PrismaModelDelegate<TModel, TId> {
75
+ const client = this.tx.getClient<PrismaClientLike>();
76
+ return this.modelDelegate(client);
77
+ }
78
+
79
+ async findById(id: TId): Promise<TDomain | null> {
80
+ const m = await this.model.findUnique({ where: { id } });
81
+ return m ? this.toDomain(m) : null;
82
+ }
83
+
84
+ async findOne(criteria: Partial<TDomain>): Promise<TDomain | null> {
85
+ const where = this.toPersistenceUpdate(criteria);
86
+ const m = await this.model.findFirst({ where });
87
+ return m ? this.toDomain(m) : null;
88
+ }
89
+
90
+ async findAll(page: IPageOption): Promise<IPageResult<TDomain>> {
91
+ const { skip, take } = resolvePageOption(page);
92
+ const [rows, total] = await Promise.all([
93
+ this.model.findMany({ skip, take }),
94
+ this.model.count({ where: undefined }),
95
+ ]);
96
+ return new Page<TDomain>(page, total, rows.map((r) => this.toDomain(r)));
97
+ }
98
+
99
+ async count(criteria?: Partial<TDomain>): Promise<number> {
100
+ if (!criteria) return this.model.count({});
101
+ const where = this.toPersistenceUpdate(criteria);
102
+ return this.model.count({ where });
103
+ }
104
+
105
+ async create(input: TDomain): Promise<TDomain> {
106
+ const data = this.toPersistenceCreate(input);
107
+ const created = await this.model.create({ data });
108
+ return this.toDomain(created);
109
+ }
110
+
111
+ async update(id: TId, patch: Partial<TDomain>): Promise<TDomain> {
112
+ const data = this.toPersistenceUpdate(patch);
113
+ const updated = await this.model.update({ where: { id }, data });
114
+ return this.toDomain(updated);
115
+ }
116
+
117
+ async delete(id: TId): Promise<void> {
118
+ await this.model.delete({ where: { id } });
119
+ }
120
+ }
@@ -0,0 +1 @@
1
+ export * from './abstract-prisma.repository';
@@ -1 +1,2 @@
1
1
  export * from './prisma-transaction-manager';
2
+ export * from './prisma-transaction.constants';
@@ -1,13 +1,17 @@
1
- import { Injectable, Inject } from '@nestjs/common';
1
+ import { Injectable, Inject, Optional } from '@nestjs/common';
2
2
  import { AsyncLocalStorage } from 'async_hooks';
3
3
  import { ITransactionManager } from '@nathapp/nestjs-data';
4
4
  import { PrismaClientLike } from '../prisma.interfaces';
5
5
  import { getPrismaToken } from '../prisma.constants';
6
+ import { PRISMA_TRANSACTION_ALS } from './prisma-transaction.constants';
6
7
 
7
8
  /**
8
9
  * Prisma implementation of ITransactionManager using AsyncLocalStorage.
9
10
  * Provides automatic transaction management with support for nested transactions.
10
11
  *
12
+ * Can accept an external AsyncLocalStorage instance (via PRISMA_TRANSACTION_ALS token)
13
+ * to share context with the transparent proxy in PrismaModule.
14
+ *
11
15
  * @example
12
16
  * ```typescript
13
17
  * @Injectable()
@@ -31,11 +35,14 @@ import { getPrismaToken } from '../prisma.constants';
31
35
  */
32
36
  @Injectable()
33
37
  export class PrismaTransactionManager implements ITransactionManager {
34
- private readonly als = new AsyncLocalStorage<PrismaClientLike>();
38
+ private readonly als: AsyncLocalStorage<PrismaClientLike>;
35
39
 
36
40
  constructor(
37
41
  @Inject(getPrismaToken()) private readonly prisma: PrismaClientLike & { $transaction: Function },
38
- ) {}
42
+ @Optional() @Inject(PRISMA_TRANSACTION_ALS) externalAls?: AsyncLocalStorage<PrismaClientLike>,
43
+ ) {
44
+ this.als = externalAls ?? new AsyncLocalStorage<PrismaClientLike>();
45
+ }
39
46
 
40
47
  /**
41
48
  * Execute fn within a transaction.
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Injection token for the shared AsyncLocalStorage instance
3
+ * used by both the transparent proxy and PrismaTransactionManager.
4
+ */
5
+ export const PRISMA_TRANSACTION_ALS = Symbol('PRISMA_TRANSACTION_ALS');
6
+
7
+ /**
8
+ * Get a named ALS token for multi-database setups.
9
+ */
10
+ export const getPrismaTransactionAlsToken = (name?: string): symbol | string =>
11
+ name && name !== 'default'
12
+ ? `PRISMA_TRANSACTION_ALS_${name}`
13
+ : PRISMA_TRANSACTION_ALS as any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "3.0.1",
3
+ "version": "3.1.1",
4
4
  "description": "NestJS Prisma integration with multi-database support",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -14,7 +14,7 @@
14
14
  "main": "dist/index.js",
15
15
  "dependencies": {
16
16
  "@nathapp/nestjs-common": "^3.0.0",
17
- "@nathapp/nestjs-data": "^3.0.1"
17
+ "@nathapp/nestjs-data": "^3.0.2"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@nathapp/eslint-config": "1.0.1",
@@ -8,6 +8,10 @@
8
8
  "rootDir": "../",
9
9
  "testEnvironment": "node",
10
10
  "testRegex": ".spec.ts$",
11
+ "moduleNameMapper": {
12
+ "^@nathapp/nestjs-common$": "<rootDir>/../nestjs-common/lib/index.ts",
13
+ "^@nathapp/nestjs-data$": "<rootDir>/../nestjs-data/lib/index.ts"
14
+ },
11
15
  "transform": {
12
16
  "^.+\\.(t)s$": [
13
17
  "ts-jest",
@@ -0,0 +1,157 @@
1
+ import { ITransactionManager } from '@nathapp/nestjs-data';
2
+ import { AbstractPrismaRepository } from '../../lib/repository/abstract-prisma.repository';
3
+ import { PrismaClientLike } from '../../lib/prisma.interfaces';
4
+
5
+ interface UserDomain {
6
+ id: string;
7
+ email: string;
8
+ name: string;
9
+ }
10
+
11
+ interface UserModel {
12
+ id: string;
13
+ emailAddress: string;
14
+ fullName: string;
15
+ }
16
+
17
+ interface UserDelegate {
18
+ findUnique(args: { where: { id: string } }): Promise<UserModel | null>;
19
+ findFirst(args: { where: any }): Promise<UserModel | null>;
20
+ findMany(args: { skip: number; take: number }): Promise<UserModel[]>;
21
+ count(args: { where?: any }): Promise<number>;
22
+ create(args: { data: UserModel }): Promise<UserModel>;
23
+ update(args: { where: { id: string }; data: Partial<UserModel> }): Promise<UserModel>;
24
+ delete(args: { where: { id: string } }): Promise<UserModel>;
25
+ }
26
+
27
+ class UserRepository extends AbstractPrismaRepository<UserDomain, UserModel, string> {
28
+ protected modelDelegate(client: any): UserDelegate {
29
+ return client.user as UserDelegate;
30
+ }
31
+ protected toDomain(m: UserModel): UserDomain {
32
+ return { id: m.id, email: m.emailAddress, name: m.fullName };
33
+ }
34
+ protected toPersistenceCreate(d: UserDomain): UserModel {
35
+ return { id: d.id, emailAddress: d.email, fullName: d.name };
36
+ }
37
+ protected toPersistenceUpdate(p: Partial<UserDomain>): Partial<UserModel> {
38
+ const out: Partial<UserModel> = {};
39
+ if (p.id !== undefined) out.id = p.id;
40
+ if (p.email !== undefined) out.emailAddress = p.email;
41
+ if (p.name !== undefined) out.fullName = p.name;
42
+ return out;
43
+ }
44
+ }
45
+
46
+ function makeFakeDelegate(): jest.Mocked<UserDelegate> {
47
+ return {
48
+ findUnique: jest.fn(),
49
+ findFirst: jest.fn(),
50
+ findMany: jest.fn(),
51
+ count: jest.fn(),
52
+ create: jest.fn(),
53
+ update: jest.fn(),
54
+ delete: jest.fn(),
55
+ };
56
+ }
57
+
58
+ function makeFakeTxManager(delegate: jest.Mocked<UserDelegate>) {
59
+ const client = { user: delegate } as unknown as PrismaClientLike;
60
+ const tx: ITransactionManager = {
61
+ run: async (fn) => fn(),
62
+ getClient: jest.fn().mockReturnValue(client),
63
+ isInTransaction: () => false,
64
+ };
65
+ return { tx };
66
+ }
67
+
68
+ describe('AbstractPrismaRepository', () => {
69
+ let delegate: jest.Mocked<UserDelegate>;
70
+ let tx: ITransactionManager;
71
+ let userRepo: UserRepository;
72
+
73
+ beforeEach(() => {
74
+ delegate = makeFakeDelegate();
75
+ ({ tx } = makeFakeTxManager(delegate));
76
+ userRepo = new UserRepository(tx);
77
+ });
78
+
79
+ it('findById maps model to domain', async () => {
80
+ delegate.findUnique.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
81
+ const user = await userRepo.findById('1');
82
+ expect(delegate.findUnique).toHaveBeenCalledWith({ where: { id: '1' } });
83
+ expect(user).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
84
+ });
85
+
86
+ it('findById returns null when not found', async () => {
87
+ delegate.findUnique.mockResolvedValue(null);
88
+ expect(await userRepo.findById('1')).toBeNull();
89
+ });
90
+
91
+ it('findOne uses findFirst with mapped criteria', async () => {
92
+ delegate.findFirst.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
93
+ const user = await userRepo.findOne({ email: 'a@b.c' });
94
+ expect(delegate.findFirst).toHaveBeenCalledWith({ where: { emailAddress: 'a@b.c' } });
95
+ expect(user).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
96
+ });
97
+
98
+ it('findOne returns null when not found', async () => {
99
+ delegate.findFirst.mockResolvedValue(null);
100
+ expect(await userRepo.findOne({ email: 'missing' })).toBeNull();
101
+ });
102
+
103
+ it('findAll paginates with findMany + count', async () => {
104
+ delegate.findMany.mockResolvedValue([{ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' }]);
105
+ delegate.count.mockResolvedValue(1);
106
+ const page = await userRepo.findAll({ current: 1, size: 10 });
107
+ expect(delegate.findMany).toHaveBeenCalledWith({ skip: 0, take: 10 });
108
+ expect(delegate.count).toHaveBeenCalledWith({ where: undefined });
109
+ expect(page.total).toBe(1);
110
+ expect(page.records).toEqual([{ id: '1', email: 'a@b.c', name: 'Alice' }]);
111
+ });
112
+
113
+ it('count without criteria delegates to count({})', async () => {
114
+ delegate.count.mockResolvedValue(7);
115
+ expect(await userRepo.count()).toBe(7);
116
+ expect(delegate.count).toHaveBeenCalledWith({});
117
+ });
118
+
119
+ it('count with criteria maps via toPersistenceUpdate', async () => {
120
+ delegate.count.mockResolvedValue(2);
121
+ expect(await userRepo.count({ email: 'a@b.c' })).toBe(2);
122
+ expect(delegate.count).toHaveBeenCalledWith({ where: { emailAddress: 'a@b.c' } });
123
+ });
124
+
125
+ it('create maps domain → model and back', async () => {
126
+ delegate.create.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
127
+ const created = await userRepo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
128
+ expect(delegate.create).toHaveBeenCalledWith({
129
+ data: { id: '1', emailAddress: 'a@b.c', fullName: 'Alice' },
130
+ });
131
+ expect(created).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
132
+ });
133
+
134
+ it('update sends mapped patch and returns mapped domain', async () => {
135
+ delegate.update.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alicia' });
136
+ const updated = await userRepo.update('1', { name: 'Alicia' });
137
+ expect(delegate.update).toHaveBeenCalledWith({
138
+ where: { id: '1' },
139
+ data: { fullName: 'Alicia' },
140
+ });
141
+ expect(updated).toEqual({ id: '1', email: 'a@b.c', name: 'Alicia' });
142
+ });
143
+
144
+ it('delete delegates to model.delete', async () => {
145
+ delegate.delete.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
146
+ await userRepo.delete('1');
147
+ expect(delegate.delete).toHaveBeenCalledWith({ where: { id: '1' } });
148
+ });
149
+
150
+ it('REGRESSION: getClient is called per operation, never cached', async () => {
151
+ delegate.findUnique.mockResolvedValue(null);
152
+ await userRepo.findById('1');
153
+ await userRepo.findById('2');
154
+ await userRepo.findById('3');
155
+ expect((tx.getClient as jest.Mock).mock.calls.length).toBeGreaterThanOrEqual(3);
156
+ });
157
+ });