@nathapp/nestjs-prisma 3.1.0 → 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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @nathapp/nestjs-prisma@3.1.0 build
2
+ > @nathapp/nestjs-prisma@3.1.1 build
3
3
  > rimraf dist && tsc -p tsconfig.json
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @nathapp/nestjs-prisma
2
2
 
3
+ ## 3.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - a448f5b: add irepository and abstract repository
8
+ - Updated dependencies [a448f5b]
9
+ - @nathapp/nestjs-data@3.0.2
10
+
3
11
  ## 3.1.0
4
12
 
5
13
  ### Minor Changes
package/CLAUDE.md CHANGED
@@ -12,6 +12,41 @@ Prisma 6 wrapper with multi-database support.
12
12
  - `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-db flexibility.
13
13
  - Pagination uses `Page<T>` from `@nathapp/nestjs-common`.
14
14
 
15
+ ## Portable Repository
16
+
17
+ `AbstractPrismaRepository<TDomain, TModel, TId>` implements
18
+ `IRepository<TDomain, TId>` from `@nathapp/nestjs-data`. Use it when services
19
+ should depend on the portable interface (decoupled from Prisma).
20
+
21
+ Note: PrismaModule's transparent transaction proxy already auto-routes
22
+ `prismaService.client.<model>.x()` to the active transaction client when
23
+ `transaction: true`. The abstract repo's value is the `IRepository` contract
24
+ (decoupling), not transaction wiring.
25
+
26
+ **Limitations:**
27
+ - Assumes a single Prisma database (the one bound to the `TRANSACTION_MANAGER`
28
+ token). Multi-DB Prisma setups expose only one tx manager today — per-DB tx
29
+ managers are a future enhancement.
30
+ - Structurally assumes the primary key property is named `"id"`. Schemas using a
31
+ different PK name must bypass this base class.
32
+
33
+ Wiring example:
34
+
35
+ ```typescript
36
+ @Injectable()
37
+ export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
38
+ constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
39
+ protected modelDelegate(client: any) { return client.user; }
40
+ // ...mapper implementations
41
+ }
42
+
43
+ // Module:
44
+ providers: [
45
+ PrismaUserRepository,
46
+ { provide: USER_REPOSITORY, useExisting: PrismaUserRepository },
47
+ ]
48
+ ```
49
+
15
50
  ## Gotchas
16
51
  - Error-case tests must use `await expect(module.compile()).rejects.toThrow()` — NestJS `compile()` eagerly instantiates providers.
17
52
  - `prisma` is a peer dependency — consumers must install it.
package/dist/index.d.ts CHANGED
@@ -9,3 +9,4 @@ export * from './testing';
9
9
  export * from './errors/prisma-error.mapper';
10
10
  export * from './filter/prisma-exception.filter';
11
11
  export * from './transaction';
12
+ export * from './repository';
package/dist/index.js CHANGED
@@ -25,4 +25,5 @@ __exportStar(require("./testing"), exports);
25
25
  __exportStar(require("./errors/prisma-error.mapper"), exports);
26
26
  __exportStar(require("./filter/prisma-exception.filter"), exports);
27
27
  __exportStar(require("./transaction"), exports);
28
+ __exportStar(require("./repository"), exports);
28
29
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,sDAAoC;AACpC,kDAAgC;AAChC,mDAAiC;AACjC,qDAAmC;AACnC,kDAAgC;AAChC,+CAA6B;AAC7B,4CAA0B;AAC1B,+DAA6C;AAC7C,mEAAiD;AACjD,gDAA8B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,sDAAoC;AACpC,kDAAgC;AAChC,mDAAiC;AACjC,qDAAmC;AACnC,kDAAgC;AAChC,+CAA6B;AAC7B,4CAA0B;AAC1B,+DAA6C;AAC7C,mEAAiD;AACjD,gDAA8B;AAC9B,+CAA6B"}
@@ -0,0 +1,51 @@
1
+ import { IPageResult, IRepository, ITransactionManager } from '@nathapp/nestjs-data';
2
+ import type { IPageOption } from '@nathapp/nestjs-common';
3
+ import { PrismaClientLike } from '../prisma.interfaces';
4
+ export interface PrismaModelDelegate<TModel, TId> {
5
+ findUnique(args: {
6
+ where: {
7
+ id: TId;
8
+ };
9
+ }): Promise<TModel | null>;
10
+ findFirst(args: {
11
+ where: any;
12
+ }): Promise<TModel | null>;
13
+ findMany(args: {
14
+ skip: number;
15
+ take: number;
16
+ where?: any;
17
+ }): Promise<TModel[]>;
18
+ count(args: {
19
+ where?: any;
20
+ }): Promise<number>;
21
+ create(args: {
22
+ data: any;
23
+ }): Promise<TModel>;
24
+ update(args: {
25
+ where: {
26
+ id: TId;
27
+ };
28
+ data: any;
29
+ }): Promise<TModel>;
30
+ delete(args: {
31
+ where: {
32
+ id: TId;
33
+ };
34
+ }): Promise<TModel>;
35
+ }
36
+ export declare abstract class AbstractPrismaRepository<TDomain, TModel, TId = string> implements IRepository<TDomain, TId> {
37
+ protected readonly tx: ITransactionManager;
38
+ constructor(tx: ITransactionManager);
39
+ protected abstract modelDelegate(client: PrismaClientLike): PrismaModelDelegate<TModel, TId>;
40
+ protected abstract toDomain(model: TModel): TDomain;
41
+ protected abstract toPersistenceCreate(domain: TDomain): any;
42
+ protected abstract toPersistenceUpdate(patch: Partial<TDomain>): any;
43
+ protected get model(): PrismaModelDelegate<TModel, TId>;
44
+ findById(id: TId): Promise<TDomain | null>;
45
+ findOne(criteria: Partial<TDomain>): Promise<TDomain | null>;
46
+ findAll(page: IPageOption): Promise<IPageResult<TDomain>>;
47
+ count(criteria?: Partial<TDomain>): Promise<number>;
48
+ create(input: TDomain): Promise<TDomain>;
49
+ update(id: TId, patch: Partial<TDomain>): Promise<TDomain>;
50
+ delete(id: TId): Promise<void>;
51
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AbstractPrismaRepository = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const nestjs_data_1 = require("@nathapp/nestjs-data");
18
+ const nestjs_common_1 = require("@nathapp/nestjs-common");
19
+ let AbstractPrismaRepository = class AbstractPrismaRepository {
20
+ constructor(tx) {
21
+ this.tx = tx;
22
+ }
23
+ get model() {
24
+ const client = this.tx.getClient();
25
+ return this.modelDelegate(client);
26
+ }
27
+ async findById(id) {
28
+ const m = await this.model.findUnique({ where: { id } });
29
+ return m ? this.toDomain(m) : null;
30
+ }
31
+ async findOne(criteria) {
32
+ const where = this.toPersistenceUpdate(criteria);
33
+ const m = await this.model.findFirst({ where });
34
+ return m ? this.toDomain(m) : null;
35
+ }
36
+ async findAll(page) {
37
+ const { skip, take } = (0, nestjs_common_1.resolvePageOption)(page);
38
+ const [rows, total] = await Promise.all([
39
+ this.model.findMany({ skip, take }),
40
+ this.model.count({ where: undefined }),
41
+ ]);
42
+ return new nestjs_common_1.Page(page, total, rows.map((r) => this.toDomain(r)));
43
+ }
44
+ async count(criteria) {
45
+ if (!criteria)
46
+ return this.model.count({});
47
+ const where = this.toPersistenceUpdate(criteria);
48
+ return this.model.count({ where });
49
+ }
50
+ async create(input) {
51
+ const data = this.toPersistenceCreate(input);
52
+ const created = await this.model.create({ data });
53
+ return this.toDomain(created);
54
+ }
55
+ async update(id, patch) {
56
+ const data = this.toPersistenceUpdate(patch);
57
+ const updated = await this.model.update({ where: { id }, data });
58
+ return this.toDomain(updated);
59
+ }
60
+ async delete(id) {
61
+ await this.model.delete({ where: { id } });
62
+ }
63
+ };
64
+ exports.AbstractPrismaRepository = AbstractPrismaRepository;
65
+ exports.AbstractPrismaRepository = AbstractPrismaRepository = __decorate([
66
+ __param(0, (0, common_1.Inject)(nestjs_data_1.TRANSACTION_MANAGER)),
67
+ __metadata("design:paramtypes", [Object])
68
+ ], AbstractPrismaRepository);
69
+ //# sourceMappingURL=abstract-prisma.repository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstract-prisma.repository.js","sourceRoot":"","sources":["../../lib/repository/abstract-prisma.repository.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1 @@
1
+ export * from './abstract-prisma.repository';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./abstract-prisma.repository"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/repository/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA6C"}
package/lib/index.ts CHANGED
@@ -9,3 +9,4 @@ export * from './testing';
9
9
  export * from './errors/prisma-error.mapper';
10
10
  export * from './filter/prisma-exception.filter';
11
11
  export * from './transaction';
12
+ export * from './repository';
@@ -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';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "3.1.0",
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
+ });
@@ -1,201 +0,0 @@
1
-
2
- > @nathapp/nestjs-prisma@3.0.1 test
3
- > jest --config ./test/jest-test.json
4
-
5
- FAIL test/transaction.spec.ts
6
- ● Test suite failed to run
7
-
8
- Cannot find module './dist' from '../nestjs-common/index.js'
9
-
10
- Require stack:
11
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
12
- lib/errors/prisma-error.mapper.ts
13
- lib/prisma.service.ts
14
- test/transaction.spec.ts
15
-
16
- 15 | };
17
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
18
- > 17 | __exportStar(require("./dist"), exports);
19
- | ^
20
- 18 |
21
-
22
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
23
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
24
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
25
- at Object.<anonymous> (lib/prisma.service.ts:3:1)
26
- at Object.<anonymous> (test/transaction.spec.ts:2:1)
27
-
28
- FAIL test/prisma.module.spec.ts
29
- ● Test suite failed to run
30
-
31
- Cannot find module './dist' from '../nestjs-common/index.js'
32
-
33
- Require stack:
34
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
35
- lib/errors/prisma-error.mapper.ts
36
- lib/prisma.service.ts
37
- lib/prisma.module.ts
38
- test/prisma.module.spec.ts
39
-
40
- 15 | };
41
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
42
- > 17 | __exportStar(require("./dist"), exports);
43
- | ^
44
- 18 |
45
-
46
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
47
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
48
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
49
- at Object.<anonymous> (lib/prisma.service.ts:3:1)
50
- at Object.<anonymous> (lib/prisma.module.ts:3:1)
51
- at Object.<anonymous> (test/prisma.module.spec.ts:3:1)
52
-
53
- FAIL test/prisma.service.spec.ts
54
- ● Test suite failed to run
55
-
56
- Cannot find module './dist' from '../nestjs-common/index.js'
57
-
58
- Require stack:
59
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
60
- lib/errors/prisma-error.mapper.ts
61
- lib/prisma.service.ts
62
- test/prisma.service.spec.ts
63
-
64
- 15 | };
65
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
66
- > 17 | __exportStar(require("./dist"), exports);
67
- | ^
68
- 18 |
69
-
70
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
71
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
72
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
73
- at Object.<anonymous> (lib/prisma.service.ts:3:1)
74
- at Object.<anonymous> (test/prisma.service.spec.ts:2:1)
75
-
76
- FAIL test/lifecycle.spec.ts
77
- ● Test suite failed to run
78
-
79
- Cannot find module './dist' from '../nestjs-common/index.js'
80
-
81
- Require stack:
82
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
83
- lib/errors/prisma-error.mapper.ts
84
- lib/prisma.service.ts
85
- test/lifecycle.spec.ts
86
-
87
- 15 | };
88
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
89
- > 17 | __exportStar(require("./dist"), exports);
90
- | ^
91
- 18 |
92
-
93
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
94
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
95
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
96
- at Object.<anonymous> (lib/prisma.service.ts:3:1)
97
- at Object.<anonymous> (test/lifecycle.spec.ts:2:1)
98
-
99
- FAIL test/pagination/paginate.spec.ts
100
- ● Test suite failed to run
101
-
102
- Cannot find module './dist' from '../nestjs-common/index.js'
103
-
104
- Require stack:
105
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
106
- lib/pagination/paginate.ts
107
- test/pagination/paginate.spec.ts
108
-
109
- 15 | };
110
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
111
- > 17 | __exportStar(require("./dist"), exports);
112
- | ^
113
- 18 |
114
-
115
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
116
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
117
- at Object.<anonymous> (lib/pagination/paginate.ts:1:1)
118
- at Object.<anonymous> (test/pagination/paginate.spec.ts:1:1)
119
-
120
- FAIL test/prisma.decorator.spec.ts
121
- ● Test suite failed to run
122
-
123
- Cannot find module './dist' from '../nestjs-common/index.js'
124
-
125
- Require stack:
126
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
127
- lib/errors/prisma-error.mapper.ts
128
- lib/prisma.service.ts
129
- lib/prisma.module.ts
130
- test/prisma.decorator.spec.ts
131
-
132
- 15 | };
133
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
134
- > 17 | __exportStar(require("./dist"), exports);
135
- | ^
136
- 18 |
137
-
138
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
139
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
140
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
141
- at Object.<anonymous> (lib/prisma.service.ts:3:1)
142
- at Object.<anonymous> (lib/prisma.module.ts:3:1)
143
- at Object.<anonymous> (test/prisma.decorator.spec.ts:4:1)
144
-
145
- FAIL test/prisma-exception-filter.spec.ts
146
- ● Test suite failed to run
147
-
148
- Cannot find module './dist' from '../nestjs-common/index.js'
149
-
150
- Require stack:
151
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
152
- lib/errors/prisma-error.mapper.ts
153
- lib/filter/prisma-exception.filter.ts
154
- test/prisma-exception-filter.spec.ts
155
-
156
- 15 | };
157
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
158
- > 17 | __exportStar(require("./dist"), exports);
159
- | ^
160
- 18 |
161
-
162
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
163
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
164
- at Object.<anonymous> (lib/errors/prisma-error.mapper.ts:1:1)
165
- at Object.<anonymous> (lib/filter/prisma-exception.filter.ts:6:1)
166
- at Object.<anonymous> (test/prisma-exception-filter.spec.ts:6:1)
167
-
168
- FAIL test/error-mapping.spec.ts
169
- ● Test suite failed to run
170
-
171
- Cannot find module './dist' from '../nestjs-common/index.js'
172
-
173
- Require stack:
174
- /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-common/index.js
175
- test/error-mapping.spec.ts
176
-
177
- 15 | };
178
- 16 | Object.defineProperty(exports, "__esModule", { value: true });
179
- > 17 | __exportStar(require("./dist"), exports);
180
- | ^
181
- 18 |
182
-
183
- at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
184
- at Object.<anonymous> (../nestjs-common/index.js:17:14)
185
- at Object.<anonymous> (test/error-mapping.spec.ts:1:1)
186
-
187
- PASS test/prisma-transaction-manager.spec.ts
188
- PASS test/prisma.health.spec.ts
189
-
190
- Test Suites: 8 failed, 2 passed, 10 total
191
- Tests: 37 passed, 37 total
192
- Snapshots: 0 total
193
- Time: 5.12 s
194
- Ran all test suites.
195
- npm error Lifecycle script `test` failed with error:
196
- npm error code 1
197
- npm error path /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-prisma
198
- npm error workspace @nathapp/nestjs-prisma@3.0.1
199
- npm error location /home/ubuntu/subrina-coder/projects/nathapp-nestjs-core/repos/nathapp-nestjs/packages/nestjs-prisma
200
- npm error command failed
201
- npm error command sh -c jest --config ./test/jest-test.json