@hazeljs/prisma 0.2.0-beta.8 → 0.2.0-beta.81
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/LICENSE +192 -21
- package/README.md +99 -217
- package/dist/__mocks__/@prisma/client/runtime/library.d.ts +10 -0
- package/dist/__mocks__/@prisma/client/runtime/library.d.ts.map +1 -0
- package/dist/__mocks__/@prisma/client/runtime/library.js +13 -0
- package/dist/__mocks__/@prisma/client.d.ts +7 -0
- package/dist/__mocks__/@prisma/client.d.ts.map +1 -0
- package/dist/__mocks__/@prisma/client.js +11 -0
- package/dist/prisma.test.d.ts +2 -0
- package/dist/prisma.test.d.ts.map +1 -0
- package/dist/prisma.test.js +271 -0
- package/dist/repository.decorator.d.ts +1 -1
- package/dist/repository.decorator.d.ts.map +1 -1
- package/dist/repository.decorator.js +8 -1
- package/package.json +11 -5
package/LICENSE
CHANGED
|
@@ -1,21 +1,192 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2024 HazelJS Team
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
22
|
+
|
|
23
|
+
1. Definitions.
|
|
24
|
+
|
|
25
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
26
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
27
|
+
|
|
28
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
29
|
+
the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
32
|
+
other entities that control, are controlled by, or are under common
|
|
33
|
+
control with that entity. For the purposes of this definition,
|
|
34
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
35
|
+
direction or management of such entity, whether by contract or
|
|
36
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
37
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
38
|
+
|
|
39
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
40
|
+
exercising permissions granted by this License.
|
|
41
|
+
|
|
42
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
43
|
+
including but not limited to software source code, documentation
|
|
44
|
+
source, and configuration files.
|
|
45
|
+
|
|
46
|
+
"Object" form shall mean any form resulting from mechanical
|
|
47
|
+
transformation or translation of a Source form, including but
|
|
48
|
+
not limited to compiled object code, generated documentation,
|
|
49
|
+
and conversions to other media types.
|
|
50
|
+
|
|
51
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
52
|
+
Object form, made available under the License, as indicated by a
|
|
53
|
+
copyright notice that is included in or attached to the work
|
|
54
|
+
(an example is provided in the Appendix below).
|
|
55
|
+
|
|
56
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
57
|
+
form, that is based on (or derived from) the Work and for which the
|
|
58
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
59
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
60
|
+
of this License, Derivative Works shall not include works that remain
|
|
61
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
62
|
+
the Work and Derivative Works thereof.
|
|
63
|
+
|
|
64
|
+
"Contribution" shall mean any work of authorship, including
|
|
65
|
+
the original version of the Work and any modifications or additions
|
|
66
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
67
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
68
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
69
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
70
|
+
means any form of electronic, verbal, or written communication sent
|
|
71
|
+
to the Licensor or its representatives, including but not limited to
|
|
72
|
+
communication on electronic mailing lists, source code control systems,
|
|
73
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
74
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
75
|
+
excluding communication that is conspicuously marked or otherwise
|
|
76
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
77
|
+
|
|
78
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
79
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
80
|
+
subsequently incorporated within the Work.
|
|
81
|
+
|
|
82
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
83
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
84
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
85
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
86
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
87
|
+
Work and such Derivative Works in Source or Object form.
|
|
88
|
+
|
|
89
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
90
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
91
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
92
|
+
(except as stated in this section) patent license to make, have made,
|
|
93
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
94
|
+
where such license applies only to those patent claims licensable
|
|
95
|
+
by such Contributor that are necessarily infringed by their
|
|
96
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
97
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
98
|
+
institute patent litigation against any entity (including a
|
|
99
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
100
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
101
|
+
or contributory patent infringement, then any patent licenses
|
|
102
|
+
granted to You under this License for that Work shall terminate
|
|
103
|
+
as of the date such litigation is filed.
|
|
104
|
+
|
|
105
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
106
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
107
|
+
modifications, and in Source or Object form, provided that You
|
|
108
|
+
meet the following conditions:
|
|
109
|
+
|
|
110
|
+
(a) You must give any other recipients of the Work or
|
|
111
|
+
Derivative Works a copy of this License; and
|
|
112
|
+
|
|
113
|
+
(b) You must cause any modified files to carry prominent notices
|
|
114
|
+
stating that You changed the files; and
|
|
115
|
+
|
|
116
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
117
|
+
that You distribute, all copyright, patent, trademark, and
|
|
118
|
+
attribution notices from the Source form of the Work,
|
|
119
|
+
excluding those notices that do not pertain to any part of
|
|
120
|
+
the Derivative Works; and
|
|
121
|
+
|
|
122
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
123
|
+
distribution, then any Derivative Works that You distribute must
|
|
124
|
+
include a readable copy of the attribution notices contained
|
|
125
|
+
within such NOTICE file, excluding those notices that do not
|
|
126
|
+
pertain to any part of the Derivative Works, in at least one
|
|
127
|
+
of the following places: within a NOTICE text file distributed
|
|
128
|
+
as part of the Derivative Works; within the Source form or
|
|
129
|
+
documentation, if provided along with the Derivative Works; or,
|
|
130
|
+
within a display generated by the Derivative Works, if and
|
|
131
|
+
wherever such third-party notices normally appear. The contents
|
|
132
|
+
of the NOTICE file are for informational purposes only and
|
|
133
|
+
do not modify the License. You may add Your own attribution
|
|
134
|
+
notices within Derivative Works that You distribute, alongside
|
|
135
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
136
|
+
that such additional attribution notices cannot be construed
|
|
137
|
+
as modifying the License.
|
|
138
|
+
|
|
139
|
+
You may add Your own copyright statement to Your modifications and
|
|
140
|
+
may provide additional or different license terms and conditions
|
|
141
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
142
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
143
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
144
|
+
the conditions stated in this License.
|
|
145
|
+
|
|
146
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
147
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
148
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
149
|
+
this License, without any additional terms or conditions.
|
|
150
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
151
|
+
the terms of any separate license agreement you may have executed
|
|
152
|
+
with Licensor regarding such Contributions.
|
|
153
|
+
|
|
154
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
155
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
156
|
+
except as required for reasonable and customary use in describing the
|
|
157
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
158
|
+
|
|
159
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
160
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
161
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
162
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
163
|
+
implied, including, without limitation, any warranties or conditions
|
|
164
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
165
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
166
|
+
appropriateness of using or redistributing the Work and assume any
|
|
167
|
+
risks associated with Your exercise of permissions under this License.
|
|
168
|
+
|
|
169
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
170
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
171
|
+
unless required by applicable law (such as deliberate and grossly
|
|
172
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
173
|
+
liable to You for damages, including any direct, indirect, special,
|
|
174
|
+
incidental, or consequential damages of any character arising as a
|
|
175
|
+
result of this License or out of the use or inability to use the
|
|
176
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
177
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
178
|
+
other commercial damages or losses), even if such Contributor
|
|
179
|
+
has been advised of the possibility of such damages.
|
|
180
|
+
|
|
181
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
182
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
183
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
184
|
+
or other liability obligations and/or rights consistent with this
|
|
185
|
+
License. However, in accepting such obligations, You may act only
|
|
186
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
187
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
188
|
+
defend, and hold each Contributor harmless for any liability
|
|
189
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
190
|
+
of your accepting any such warranty or additional liability.
|
|
191
|
+
|
|
192
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
CHANGED
|
@@ -1,23 +1,32 @@
|
|
|
1
1
|
# @hazeljs/prisma
|
|
2
2
|
|
|
3
|
-
**Prisma
|
|
3
|
+
**Prisma + HazelJS. Type-safe, no boilerplate.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Repository pattern, `@Repository` decorator, DI integration. Full CRUD from your schema. Transactions, relations, pagination — the way you'd expect it to work.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/@hazeljs/prisma)
|
|
8
|
-
[](https://www.npmjs.com/package/@hazeljs/prisma)
|
|
9
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
9
10
|
|
|
10
11
|
## Features
|
|
11
12
|
|
|
12
13
|
- 🎯 **Type-Safe Queries** - Full TypeScript support with Prisma
|
|
13
14
|
- 🏗️ **Repository Pattern** - Clean data access layer
|
|
14
|
-
- 🎨 **Decorator Support** - `@
|
|
15
|
+
- 🎨 **Decorator Support** - `@Repository` implies `@Injectable()` — one decorator does the job
|
|
15
16
|
- 🔄 **Transaction Support** - Built-in transaction management
|
|
16
17
|
- 📊 **Query Builder** - Fluent query interface
|
|
17
18
|
- 🔌 **Dependency Injection** - Seamless DI integration
|
|
18
19
|
- 🧪 **Testing Utilities** - Mock Prisma for testing
|
|
19
20
|
- 📈 **Connection Pooling** - Automatic connection management
|
|
20
21
|
|
|
22
|
+
## Decorator Convention
|
|
23
|
+
|
|
24
|
+
| Class type | Correct decorator |
|
|
25
|
+
|------------|------------------|
|
|
26
|
+
| Repository (`extends BaseRepository`) | `@Repository({ model: '...' })` — implies `@Injectable()` |
|
|
27
|
+
| Service (business logic) | `@Service()` |
|
|
28
|
+
| Controller | `@Controller(...)` |
|
|
29
|
+
|
|
21
30
|
## Installation
|
|
22
31
|
|
|
23
32
|
```bash
|
|
@@ -92,18 +101,18 @@ export class AppModule {}
|
|
|
92
101
|
|
|
93
102
|
### 5. Create Repository
|
|
94
103
|
|
|
104
|
+
`@Repository` implies `@Injectable()` — no need to add both decorators.
|
|
105
|
+
|
|
95
106
|
```typescript
|
|
96
|
-
import {
|
|
97
|
-
import {
|
|
107
|
+
import { PrismaService, BaseRepository } from '@hazeljs/prisma';
|
|
108
|
+
import { Repository } from '@hazeljs/prisma';
|
|
98
109
|
|
|
99
|
-
@
|
|
100
|
-
|
|
101
|
-
export class UserRepository extends BaseRepository {
|
|
110
|
+
@Repository({ model: 'user' })
|
|
111
|
+
export class UserRepository extends BaseRepository<User> {
|
|
102
112
|
constructor(prisma: PrismaService) {
|
|
103
|
-
super(prisma);
|
|
113
|
+
super(prisma, 'user');
|
|
104
114
|
}
|
|
105
115
|
|
|
106
|
-
// Custom methods
|
|
107
116
|
async findByEmail(email: string) {
|
|
108
117
|
return this.prisma.user.findUnique({ where: { email } });
|
|
109
118
|
}
|
|
@@ -117,17 +126,22 @@ export class UserRepository extends BaseRepository {
|
|
|
117
126
|
}
|
|
118
127
|
```
|
|
119
128
|
|
|
120
|
-
### 6. Use in Service
|
|
129
|
+
### 6. Use in a Service
|
|
130
|
+
|
|
131
|
+
Use `@Service` for service classes — not `@Injectable`.
|
|
121
132
|
|
|
122
133
|
```typescript
|
|
123
|
-
import {
|
|
134
|
+
import { Service } from '@hazeljs/core';
|
|
135
|
+
import { InjectRepository } from '@hazeljs/prisma';
|
|
124
136
|
|
|
125
|
-
@
|
|
137
|
+
@Service()
|
|
126
138
|
export class UserService {
|
|
127
|
-
constructor(
|
|
139
|
+
constructor(
|
|
140
|
+
@InjectRepository() private readonly userRepository: UserRepository,
|
|
141
|
+
) {}
|
|
128
142
|
|
|
129
143
|
async create(data: { email: string; name: string }) {
|
|
130
|
-
return this.userRepository.create(
|
|
144
|
+
return this.userRepository.create(data);
|
|
131
145
|
}
|
|
132
146
|
|
|
133
147
|
async findAll() {
|
|
@@ -135,18 +149,15 @@ export class UserService {
|
|
|
135
149
|
}
|
|
136
150
|
|
|
137
151
|
async findOne(id: string) {
|
|
138
|
-
return this.userRepository.
|
|
152
|
+
return this.userRepository.findOne({ id });
|
|
139
153
|
}
|
|
140
154
|
|
|
141
|
-
async update(id: string, data:
|
|
142
|
-
return this.userRepository.update({
|
|
143
|
-
where: { id },
|
|
144
|
-
data,
|
|
145
|
-
});
|
|
155
|
+
async update(id: string, data: Partial<User>) {
|
|
156
|
+
return this.userRepository.update({ id }, data);
|
|
146
157
|
}
|
|
147
158
|
|
|
148
159
|
async delete(id: string) {
|
|
149
|
-
return this.userRepository.delete({
|
|
160
|
+
return this.userRepository.delete({ id });
|
|
150
161
|
}
|
|
151
162
|
}
|
|
152
163
|
```
|
|
@@ -156,52 +167,47 @@ export class UserService {
|
|
|
156
167
|
The `BaseRepository` provides common CRUD operations:
|
|
157
168
|
|
|
158
169
|
```typescript
|
|
159
|
-
class BaseRepository {
|
|
170
|
+
class BaseRepository<T> {
|
|
160
171
|
// Create
|
|
161
|
-
create(
|
|
162
|
-
createMany(args: Prisma.UserCreateManyArgs): Promise<Prisma.BatchPayload>;
|
|
172
|
+
create(data: Omit<T, 'id'>): Promise<T>;
|
|
163
173
|
|
|
164
174
|
// Read
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
count(args?: Prisma.UserCountArgs): Promise<number>;
|
|
175
|
+
findMany(): Promise<T[]>;
|
|
176
|
+
findOne(where: WhereUniqueInput): Promise<T | null>;
|
|
177
|
+
count(args?: unknown): Promise<number>;
|
|
169
178
|
|
|
170
179
|
// Update
|
|
171
|
-
update(
|
|
172
|
-
updateMany(args: Prisma.UserUpdateManyArgs): Promise<Prisma.BatchPayload>;
|
|
173
|
-
upsert(args: Prisma.UserUpsertArgs): Promise<User>;
|
|
180
|
+
update(where: WhereUniqueInput, data: UpdateInput): Promise<T>;
|
|
174
181
|
|
|
175
182
|
// Delete
|
|
176
|
-
delete(
|
|
177
|
-
deleteMany(args?: Prisma.UserDeleteManyArgs): Promise<Prisma.BatchPayload>;
|
|
183
|
+
delete(where: WhereUniqueInput): Promise<T>;
|
|
178
184
|
}
|
|
179
185
|
```
|
|
180
186
|
|
|
181
187
|
## Transactions
|
|
182
188
|
|
|
183
|
-
### Using PrismaService
|
|
189
|
+
### Using PrismaService directly
|
|
184
190
|
|
|
185
191
|
```typescript
|
|
186
|
-
@
|
|
192
|
+
import { Service } from '@hazeljs/core';
|
|
193
|
+
import { PrismaService } from '@hazeljs/prisma';
|
|
194
|
+
|
|
195
|
+
@Service()
|
|
187
196
|
export class TransferService {
|
|
188
|
-
constructor(private prisma: PrismaService) {}
|
|
197
|
+
constructor(private readonly prisma: PrismaService) {}
|
|
189
198
|
|
|
190
199
|
async transfer(fromId: string, toId: string, amount: number) {
|
|
191
200
|
return this.prisma.$transaction(async (tx) => {
|
|
192
|
-
// Deduct from sender
|
|
193
201
|
await tx.account.update({
|
|
194
202
|
where: { id: fromId },
|
|
195
203
|
data: { balance: { decrement: amount } },
|
|
196
204
|
});
|
|
197
205
|
|
|
198
|
-
// Add to receiver
|
|
199
206
|
await tx.account.update({
|
|
200
207
|
where: { id: toId },
|
|
201
208
|
data: { balance: { increment: amount } },
|
|
202
209
|
});
|
|
203
210
|
|
|
204
|
-
// Create transaction record
|
|
205
211
|
return tx.transaction.create({
|
|
206
212
|
data: { fromId, toId, amount },
|
|
207
213
|
});
|
|
@@ -210,28 +216,26 @@ export class TransferService {
|
|
|
210
216
|
}
|
|
211
217
|
```
|
|
212
218
|
|
|
213
|
-
### Using
|
|
219
|
+
### Using Repositories inside a transaction
|
|
214
220
|
|
|
215
221
|
```typescript
|
|
216
|
-
@
|
|
222
|
+
import { Service } from '@hazeljs/core';
|
|
223
|
+
import { PrismaService } from '@hazeljs/prisma';
|
|
224
|
+
|
|
225
|
+
@Service()
|
|
217
226
|
export class OrderService {
|
|
218
227
|
constructor(
|
|
219
|
-
private orderRepository: OrderRepository,
|
|
220
|
-
private inventoryRepository: InventoryRepository,
|
|
221
|
-
private prisma: PrismaService
|
|
228
|
+
private readonly orderRepository: OrderRepository,
|
|
229
|
+
private readonly inventoryRepository: InventoryRepository,
|
|
230
|
+
private readonly prisma: PrismaService,
|
|
222
231
|
) {}
|
|
223
232
|
|
|
224
233
|
async createOrder(userId: string, items: OrderItem[]) {
|
|
225
234
|
return this.prisma.$transaction(async (tx) => {
|
|
226
|
-
// Create order
|
|
227
235
|
const order = await tx.order.create({
|
|
228
|
-
data: {
|
|
229
|
-
userId,
|
|
230
|
-
items: { create: items },
|
|
231
|
-
},
|
|
236
|
+
data: { userId, items: { create: items } },
|
|
232
237
|
});
|
|
233
238
|
|
|
234
|
-
// Update inventory
|
|
235
239
|
for (const item of items) {
|
|
236
240
|
await tx.inventory.update({
|
|
237
241
|
where: { productId: item.productId },
|
|
@@ -250,8 +254,12 @@ export class OrderService {
|
|
|
250
254
|
### Relations
|
|
251
255
|
|
|
252
256
|
```typescript
|
|
253
|
-
@
|
|
254
|
-
export class UserRepository extends BaseRepository {
|
|
257
|
+
@Repository({ model: 'user' })
|
|
258
|
+
export class UserRepository extends BaseRepository<User> {
|
|
259
|
+
constructor(prisma: PrismaService) {
|
|
260
|
+
super(prisma, 'user');
|
|
261
|
+
}
|
|
262
|
+
|
|
255
263
|
async findWithRelations(id: string) {
|
|
256
264
|
return this.prisma.user.findUnique({
|
|
257
265
|
where: { id },
|
|
@@ -270,28 +278,22 @@ export class UserRepository extends BaseRepository {
|
|
|
270
278
|
### Pagination
|
|
271
279
|
|
|
272
280
|
```typescript
|
|
273
|
-
@
|
|
274
|
-
export class PostRepository extends BaseRepository {
|
|
281
|
+
@Repository({ model: 'post' })
|
|
282
|
+
export class PostRepository extends BaseRepository<Post> {
|
|
283
|
+
constructor(prisma: PrismaService) {
|
|
284
|
+
super(prisma, 'post');
|
|
285
|
+
}
|
|
286
|
+
|
|
275
287
|
async findPaginated(page: number, limit: number) {
|
|
276
288
|
const skip = (page - 1) * limit;
|
|
277
|
-
|
|
278
289
|
const [posts, total] = await Promise.all([
|
|
279
|
-
this.prisma.post.findMany({
|
|
280
|
-
skip,
|
|
281
|
-
take: limit,
|
|
282
|
-
orderBy: { createdAt: 'desc' },
|
|
283
|
-
}),
|
|
290
|
+
this.prisma.post.findMany({ skip, take: limit, orderBy: { createdAt: 'desc' } }),
|
|
284
291
|
this.prisma.post.count(),
|
|
285
292
|
]);
|
|
286
293
|
|
|
287
294
|
return {
|
|
288
295
|
data: posts,
|
|
289
|
-
meta: {
|
|
290
|
-
page,
|
|
291
|
-
limit,
|
|
292
|
-
total,
|
|
293
|
-
totalPages: Math.ceil(total / limit),
|
|
294
|
-
},
|
|
296
|
+
meta: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
|
295
297
|
};
|
|
296
298
|
}
|
|
297
299
|
}
|
|
@@ -300,8 +302,12 @@ export class PostRepository extends BaseRepository {
|
|
|
300
302
|
### Filtering
|
|
301
303
|
|
|
302
304
|
```typescript
|
|
303
|
-
@
|
|
304
|
-
export class ProductRepository extends BaseRepository {
|
|
305
|
+
@Repository({ model: 'product' })
|
|
306
|
+
export class ProductRepository extends BaseRepository<Product> {
|
|
307
|
+
constructor(prisma: PrismaService) {
|
|
308
|
+
super(prisma, 'product');
|
|
309
|
+
}
|
|
310
|
+
|
|
305
311
|
async search(query: string, filters: {
|
|
306
312
|
category?: string;
|
|
307
313
|
minPrice?: number;
|
|
@@ -311,12 +317,10 @@ export class ProductRepository extends BaseRepository {
|
|
|
311
317
|
return this.prisma.product.findMany({
|
|
312
318
|
where: {
|
|
313
319
|
AND: [
|
|
314
|
-
{
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
],
|
|
319
|
-
},
|
|
320
|
+
{ OR: [
|
|
321
|
+
{ name: { contains: query, mode: 'insensitive' } },
|
|
322
|
+
{ description: { contains: query, mode: 'insensitive' } },
|
|
323
|
+
]},
|
|
320
324
|
filters.category ? { category: filters.category } : {},
|
|
321
325
|
filters.minPrice ? { price: { gte: filters.minPrice } } : {},
|
|
322
326
|
filters.maxPrice ? { price: { lte: filters.maxPrice } } : {},
|
|
@@ -331,9 +335,12 @@ export class ProductRepository extends BaseRepository {
|
|
|
331
335
|
### Aggregations
|
|
332
336
|
|
|
333
337
|
```typescript
|
|
334
|
-
@
|
|
335
|
-
|
|
336
|
-
|
|
338
|
+
import { Service } from '@hazeljs/core';
|
|
339
|
+
import { PrismaService } from '@hazeljs/prisma';
|
|
340
|
+
|
|
341
|
+
@Service()
|
|
342
|
+
export class AnalyticsService {
|
|
343
|
+
constructor(private readonly prisma: PrismaService) {}
|
|
337
344
|
|
|
338
345
|
async getOrderStats() {
|
|
339
346
|
return this.prisma.order.aggregate({
|
|
@@ -364,18 +371,18 @@ export class AnalyticsRepository {
|
|
|
364
371
|
Add Prisma middleware for logging, soft deletes, etc:
|
|
365
372
|
|
|
366
373
|
```typescript
|
|
374
|
+
import { Injectable } from '@hazeljs/core';
|
|
375
|
+
import { PrismaClient } from '@prisma/client';
|
|
376
|
+
|
|
367
377
|
@Injectable()
|
|
368
378
|
export class PrismaService extends PrismaClient {
|
|
369
379
|
constructor() {
|
|
370
380
|
super();
|
|
371
381
|
|
|
372
|
-
// Logging middleware
|
|
373
382
|
this.$use(async (params, next) => {
|
|
374
383
|
const before = Date.now();
|
|
375
384
|
const result = await next(params);
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
console.log(`Query ${params.model}.${params.action} took ${after - before}ms`);
|
|
385
|
+
console.log(`Query ${params.model}.${params.action} took ${Date.now() - before}ms`);
|
|
379
386
|
return result;
|
|
380
387
|
});
|
|
381
388
|
|
|
@@ -385,16 +392,6 @@ export class PrismaService extends PrismaClient {
|
|
|
385
392
|
params.action = 'update';
|
|
386
393
|
params.args['data'] = { deletedAt: new Date() };
|
|
387
394
|
}
|
|
388
|
-
|
|
389
|
-
if (params.action === 'deleteMany') {
|
|
390
|
-
params.action = 'updateMany';
|
|
391
|
-
if (params.args.data != undefined) {
|
|
392
|
-
params.args.data['deletedAt'] = new Date();
|
|
393
|
-
} else {
|
|
394
|
-
params.args['data'] = { deletedAt: new Date() };
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
|
|
398
395
|
return next(params);
|
|
399
396
|
});
|
|
400
397
|
}
|
|
@@ -410,41 +407,18 @@ import { PrismaClient } from '@prisma/client';
|
|
|
410
407
|
const prisma = new PrismaClient();
|
|
411
408
|
|
|
412
409
|
async function main() {
|
|
413
|
-
|
|
414
|
-
const alice = await prisma.user.create({
|
|
410
|
+
await prisma.user.create({
|
|
415
411
|
data: {
|
|
416
412
|
email: 'alice@example.com',
|
|
417
413
|
name: 'Alice',
|
|
418
|
-
posts: {
|
|
419
|
-
create: [
|
|
420
|
-
{
|
|
421
|
-
title: 'First Post',
|
|
422
|
-
content: 'Hello World!',
|
|
423
|
-
published: true,
|
|
424
|
-
},
|
|
425
|
-
],
|
|
426
|
-
},
|
|
427
|
-
},
|
|
428
|
-
});
|
|
429
|
-
|
|
430
|
-
const bob = await prisma.user.create({
|
|
431
|
-
data: {
|
|
432
|
-
email: 'bob@example.com',
|
|
433
|
-
name: 'Bob',
|
|
414
|
+
posts: { create: [{ title: 'First Post', content: 'Hello World!', published: true }] },
|
|
434
415
|
},
|
|
435
416
|
});
|
|
436
|
-
|
|
437
|
-
console.log({ alice, bob });
|
|
438
417
|
}
|
|
439
418
|
|
|
440
419
|
main()
|
|
441
|
-
.catch((e) => {
|
|
442
|
-
|
|
443
|
-
process.exit(1);
|
|
444
|
-
})
|
|
445
|
-
.finally(async () => {
|
|
446
|
-
await prisma.$disconnect();
|
|
447
|
-
});
|
|
420
|
+
.catch((e) => { console.error(e); process.exit(1); })
|
|
421
|
+
.finally(() => prisma.$disconnect());
|
|
448
422
|
```
|
|
449
423
|
|
|
450
424
|
Add to `package.json`:
|
|
@@ -463,114 +437,22 @@ Run seed:
|
|
|
463
437
|
npx prisma db seed
|
|
464
438
|
```
|
|
465
439
|
|
|
466
|
-
## Testing
|
|
467
|
-
|
|
468
|
-
### Mock Prisma Service
|
|
469
|
-
|
|
470
|
-
```typescript
|
|
471
|
-
import { TestingModule } from '@hazeljs/core';
|
|
472
|
-
import { UserService } from './user.service';
|
|
473
|
-
import { UserRepository } from './user.repository';
|
|
474
|
-
|
|
475
|
-
describe('UserService', () => {
|
|
476
|
-
let service: UserService;
|
|
477
|
-
let repository: UserRepository;
|
|
478
|
-
|
|
479
|
-
const mockPrisma = {
|
|
480
|
-
user: {
|
|
481
|
-
create: jest.fn(),
|
|
482
|
-
findMany: jest.fn(),
|
|
483
|
-
findUnique: jest.fn(),
|
|
484
|
-
update: jest.fn(),
|
|
485
|
-
delete: jest.fn(),
|
|
486
|
-
},
|
|
487
|
-
};
|
|
488
|
-
|
|
489
|
-
beforeEach(async () => {
|
|
490
|
-
const module = await TestingModule.create({
|
|
491
|
-
providers: [
|
|
492
|
-
UserService,
|
|
493
|
-
{
|
|
494
|
-
provide: UserRepository,
|
|
495
|
-
useValue: {
|
|
496
|
-
create: mockPrisma.user.create,
|
|
497
|
-
findMany: mockPrisma.user.findMany,
|
|
498
|
-
findUnique: mockPrisma.user.findUnique,
|
|
499
|
-
update: mockPrisma.user.update,
|
|
500
|
-
delete: mockPrisma.user.delete,
|
|
501
|
-
},
|
|
502
|
-
},
|
|
503
|
-
],
|
|
504
|
-
});
|
|
505
|
-
|
|
506
|
-
service = module.get(UserService);
|
|
507
|
-
repository = module.get(UserRepository);
|
|
508
|
-
});
|
|
509
|
-
|
|
510
|
-
it('should create a user', async () => {
|
|
511
|
-
const userData = { email: 'test@example.com', name: 'Test' };
|
|
512
|
-
mockPrisma.user.create.mockResolvedValue({ id: '1', ...userData });
|
|
513
|
-
|
|
514
|
-
const result = await service.create(userData);
|
|
515
|
-
|
|
516
|
-
expect(result).toEqual({ id: '1', ...userData });
|
|
517
|
-
expect(mockPrisma.user.create).toHaveBeenCalledWith({ data: userData });
|
|
518
|
-
});
|
|
519
|
-
});
|
|
520
|
-
```
|
|
521
|
-
|
|
522
|
-
## Best Practices
|
|
523
|
-
|
|
524
|
-
1. **Use Repositories** - Encapsulate data access logic
|
|
525
|
-
2. **Type Safety** - Leverage Prisma's generated types
|
|
526
|
-
3. **Transactions** - Use transactions for related operations
|
|
527
|
-
4. **Indexes** - Add indexes for frequently queried fields
|
|
528
|
-
5. **Migrations** - Always use migrations, never modify schema directly
|
|
529
|
-
6. **Connection Pooling** - Configure appropriate pool size
|
|
530
|
-
7. **Error Handling** - Handle Prisma errors gracefully
|
|
531
|
-
8. **Soft Deletes** - Implement soft deletes with middleware
|
|
532
|
-
|
|
533
440
|
## Migration Commands
|
|
534
441
|
|
|
535
442
|
```bash
|
|
536
|
-
# Create migration
|
|
537
443
|
npx prisma migrate dev --name add_user_role
|
|
538
|
-
|
|
539
|
-
# Apply migrations
|
|
540
444
|
npx prisma migrate deploy
|
|
541
|
-
|
|
542
|
-
# Reset database
|
|
543
445
|
npx prisma migrate reset
|
|
544
|
-
|
|
545
|
-
# Generate client
|
|
546
446
|
npx prisma generate
|
|
547
|
-
|
|
548
|
-
# Open Prisma Studio
|
|
549
447
|
npx prisma studio
|
|
550
448
|
```
|
|
551
449
|
|
|
552
|
-
##
|
|
553
|
-
|
|
554
|
-
See the [examples](../../example/src/prisma) directory for complete working examples.
|
|
555
|
-
|
|
556
|
-
## Testing
|
|
557
|
-
|
|
558
|
-
```bash
|
|
559
|
-
npm test
|
|
560
|
-
```
|
|
561
|
-
|
|
562
|
-
## Contributing
|
|
450
|
+
## Links
|
|
563
451
|
|
|
564
|
-
|
|
452
|
+
- [TypeORM docs](https://www.prisma.io/docs)
|
|
453
|
+
- [HazelJS](https://hazeljs.com)
|
|
454
|
+
- [GitHub](https://github.com/hazel-js/hazeljs)
|
|
565
455
|
|
|
566
456
|
## License
|
|
567
457
|
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
## Links
|
|
571
|
-
|
|
572
|
-
- [Documentation](https://hazeljs.com/docs/packages/prisma)
|
|
573
|
-
- [Prisma Docs](https://www.prisma.io/docs)
|
|
574
|
-
- [GitHub](https://github.com/hazel-js/hazeljs)
|
|
575
|
-
- [Issues](https://github.com/hazeljs/hazel-js/issues)
|
|
576
|
-
- [Discord](https://discord.gg/hazeljs)
|
|
458
|
+
Apache 2.0 © [HazelJS](https://hazeljs.com)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare class PrismaClientKnownRequestError extends Error {
|
|
2
|
+
code: string;
|
|
3
|
+
meta?: Record<string, unknown>;
|
|
4
|
+
clientVersion: string;
|
|
5
|
+
constructor(message: string, { code, meta }: {
|
|
6
|
+
code: string;
|
|
7
|
+
meta?: Record<string, unknown>;
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=library.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"library.d.ts","sourceRoot":"","sources":["../../../../../src/__mocks__/@prisma/client/runtime/library.ts"],"names":[],"mappings":"AAAA,qBAAa,6BAA8B,SAAQ,KAAK;IACtD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,aAAa,EAAE,MAAM,CAAC;gBAEV,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE;CAO9F"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrismaClientKnownRequestError = void 0;
|
|
4
|
+
class PrismaClientKnownRequestError extends Error {
|
|
5
|
+
constructor(message, { code, meta }) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'PrismaClientKnownRequestError';
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.meta = meta;
|
|
10
|
+
this.clientVersion = '5.0.0';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.PrismaClientKnownRequestError = PrismaClientKnownRequestError;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/__mocks__/@prisma/client.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAY;IACvB,GAAG,2BAAa;IAChB,QAAQ,2BAA0C;IAClD,WAAW,2BAA0C;gBAEzC,QAAQ,CAAC,EAAE,OAAO;CAC/B"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrismaClient = void 0;
|
|
4
|
+
class PrismaClient {
|
|
5
|
+
constructor(_options) {
|
|
6
|
+
this.$on = jest.fn();
|
|
7
|
+
this.$connect = jest.fn().mockResolvedValue(undefined);
|
|
8
|
+
this.$disconnect = jest.fn().mockResolvedValue(undefined);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.PrismaClient = PrismaClient;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prisma.test.d.ts","sourceRoot":"","sources":["../src/prisma.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/// <reference types="jest" />
|
|
3
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
4
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
5
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
6
|
+
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;
|
|
7
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
8
|
+
};
|
|
9
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
10
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
11
|
+
};
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
jest.mock('@hazeljs/core', () => ({
|
|
14
|
+
__esModule: true,
|
|
15
|
+
Injectable: () => () => undefined,
|
|
16
|
+
HazelModule: () => () => undefined,
|
|
17
|
+
Module: () => () => undefined,
|
|
18
|
+
RepositoryOptions: class {
|
|
19
|
+
},
|
|
20
|
+
logger: { info: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
|
21
|
+
default: { info: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
|
22
|
+
}));
|
|
23
|
+
const core_1 = __importDefault(require("@hazeljs/core"));
|
|
24
|
+
const prisma_service_1 = require("./prisma.service");
|
|
25
|
+
const base_repository_1 = require("./base.repository");
|
|
26
|
+
const repository_decorator_1 = require("./repository.decorator");
|
|
27
|
+
const library_1 = require("./__mocks__/@prisma/client/runtime/library");
|
|
28
|
+
// ─── PrismaService ────────────────────────────────────────────────────────────
|
|
29
|
+
describe('PrismaService', () => {
|
|
30
|
+
let service;
|
|
31
|
+
let $onMock;
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
service = new prisma_service_1.PrismaService();
|
|
34
|
+
$onMock = service.$on;
|
|
35
|
+
});
|
|
36
|
+
it('instantiates without error', () => {
|
|
37
|
+
expect(service).toBeDefined();
|
|
38
|
+
});
|
|
39
|
+
it('registers $on handler for query events', () => {
|
|
40
|
+
expect($onMock).toHaveBeenCalledWith('query', expect.any(Function));
|
|
41
|
+
});
|
|
42
|
+
it('registers $on handler for error events', () => {
|
|
43
|
+
expect($onMock).toHaveBeenCalledWith('error', expect.any(Function));
|
|
44
|
+
});
|
|
45
|
+
it('query event callback logs valid query events', () => {
|
|
46
|
+
const queryCallback = $onMock.mock.calls.find(([evt]) => evt === 'query')?.[1];
|
|
47
|
+
expect(queryCallback).toBeDefined();
|
|
48
|
+
queryCallback({ query: 'SELECT 1', params: '[]', duration: 5 });
|
|
49
|
+
expect(core_1.default.debug).toHaveBeenCalled();
|
|
50
|
+
});
|
|
51
|
+
it('query event callback ignores non-query events', () => {
|
|
52
|
+
const queryCallback = $onMock.mock.calls.find(([evt]) => evt === 'query')?.[1];
|
|
53
|
+
jest.clearAllMocks();
|
|
54
|
+
queryCallback({ message: 'not a query event' });
|
|
55
|
+
expect(core_1.default.debug).not.toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
it('error event callback logs prisma error events', () => {
|
|
58
|
+
const errorCallback = $onMock.mock.calls.find(([evt]) => evt === 'error')?.[1];
|
|
59
|
+
expect(errorCallback).toBeDefined();
|
|
60
|
+
errorCallback({ message: 'some error' });
|
|
61
|
+
expect(core_1.default.error).toHaveBeenCalled();
|
|
62
|
+
});
|
|
63
|
+
it('error event callback ignores events without message', () => {
|
|
64
|
+
const errorCallback = $onMock.mock.calls.find(([evt]) => evt === 'error')?.[1];
|
|
65
|
+
jest.clearAllMocks();
|
|
66
|
+
errorCallback({ query: 'SELECT 1', params: '[]', duration: 2 });
|
|
67
|
+
expect(core_1.default.error).not.toHaveBeenCalled();
|
|
68
|
+
});
|
|
69
|
+
it('onModuleInit calls $connect and resolves', async () => {
|
|
70
|
+
await expect(service.onModuleInit()).resolves.toBeUndefined();
|
|
71
|
+
expect(service.$connect).toHaveBeenCalled();
|
|
72
|
+
});
|
|
73
|
+
it('onModuleInit throws and logs when $connect rejects', async () => {
|
|
74
|
+
service.$connect.mockRejectedValueOnce(new Error('connection refused'));
|
|
75
|
+
await expect(service.onModuleInit()).rejects.toThrow('connection refused');
|
|
76
|
+
});
|
|
77
|
+
it('onModuleDestroy calls $disconnect and resolves', async () => {
|
|
78
|
+
await expect(service.onModuleDestroy()).resolves.toBeUndefined();
|
|
79
|
+
expect(service.$disconnect).toHaveBeenCalled();
|
|
80
|
+
});
|
|
81
|
+
it('onModuleDestroy throws and logs when $disconnect rejects', async () => {
|
|
82
|
+
service.$disconnect.mockRejectedValueOnce(new Error('disconnect failed'));
|
|
83
|
+
await expect(service.onModuleDestroy()).rejects.toThrow('disconnect failed');
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
function buildMockDelegate() {
|
|
87
|
+
return {
|
|
88
|
+
findMany: jest.fn(),
|
|
89
|
+
findUnique: jest.fn(),
|
|
90
|
+
create: jest.fn(),
|
|
91
|
+
update: jest.fn(),
|
|
92
|
+
delete: jest.fn(),
|
|
93
|
+
count: jest.fn(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
class TestRepository extends base_repository_1.BaseRepository {
|
|
97
|
+
constructor(prisma) {
|
|
98
|
+
super(prisma, 'testModel');
|
|
99
|
+
}
|
|
100
|
+
// Expose protected handleError for testing
|
|
101
|
+
testHandleError(error) {
|
|
102
|
+
return this.handleError(error);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function buildRepo() {
|
|
106
|
+
const delegate = buildMockDelegate();
|
|
107
|
+
const mockPrisma = {
|
|
108
|
+
$on: jest.fn(),
|
|
109
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
110
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
111
|
+
testModel: delegate,
|
|
112
|
+
};
|
|
113
|
+
const repo = new TestRepository(mockPrisma);
|
|
114
|
+
return { repo, delegate };
|
|
115
|
+
}
|
|
116
|
+
describe('BaseRepository', () => {
|
|
117
|
+
describe('findMany()', () => {
|
|
118
|
+
it('returns all records', async () => {
|
|
119
|
+
const { repo, delegate } = buildRepo();
|
|
120
|
+
const records = [
|
|
121
|
+
{ id: 1, name: 'Alice' },
|
|
122
|
+
{ id: 2, name: 'Bob' },
|
|
123
|
+
];
|
|
124
|
+
delegate.findMany.mockResolvedValue(records);
|
|
125
|
+
await expect(repo.findMany()).resolves.toEqual(records);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
describe('findOne()', () => {
|
|
129
|
+
it('returns matching record', async () => {
|
|
130
|
+
const { repo, delegate } = buildRepo();
|
|
131
|
+
const record = { id: 1, name: 'Alice' };
|
|
132
|
+
delegate.findUnique.mockResolvedValue(record);
|
|
133
|
+
await expect(repo.findOne({ id: 1 })).resolves.toEqual(record);
|
|
134
|
+
expect(delegate.findUnique).toHaveBeenCalledWith({ where: { id: 1 } });
|
|
135
|
+
});
|
|
136
|
+
it('returns null when not found', async () => {
|
|
137
|
+
const { repo, delegate } = buildRepo();
|
|
138
|
+
delegate.findUnique.mockResolvedValue(null);
|
|
139
|
+
await expect(repo.findOne({ id: 99 })).resolves.toBeNull();
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
describe('create()', () => {
|
|
143
|
+
it('creates and returns a record', async () => {
|
|
144
|
+
const { repo, delegate } = buildRepo();
|
|
145
|
+
const created = { id: 3, name: 'Charlie' };
|
|
146
|
+
delegate.create.mockResolvedValue(created);
|
|
147
|
+
await expect(repo.create({ name: 'Charlie' })).resolves.toEqual(created);
|
|
148
|
+
expect(delegate.create).toHaveBeenCalledWith({ data: { name: 'Charlie' } });
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
describe('update()', () => {
|
|
152
|
+
it('updates and returns the updated record', async () => {
|
|
153
|
+
const { repo, delegate } = buildRepo();
|
|
154
|
+
const updated = { id: 1, name: 'Updated' };
|
|
155
|
+
delegate.update.mockResolvedValue(updated);
|
|
156
|
+
await expect(repo.update({ id: 1 }, { name: 'Updated' })).resolves.toEqual(updated);
|
|
157
|
+
expect(delegate.update).toHaveBeenCalledWith({ where: { id: 1 }, data: { name: 'Updated' } });
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
describe('delete()', () => {
|
|
161
|
+
it('deletes and returns the deleted record', async () => {
|
|
162
|
+
const { repo, delegate } = buildRepo();
|
|
163
|
+
const deleted = { id: 1, name: 'Alice' };
|
|
164
|
+
delegate.delete.mockResolvedValue(deleted);
|
|
165
|
+
await expect(repo.delete({ id: 1 })).resolves.toEqual(deleted);
|
|
166
|
+
expect(delegate.delete).toHaveBeenCalledWith({ where: { id: 1 } });
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
describe('count()', () => {
|
|
170
|
+
it('returns record count', async () => {
|
|
171
|
+
const { repo, delegate } = buildRepo();
|
|
172
|
+
delegate.count.mockResolvedValue(5);
|
|
173
|
+
await expect(repo.count()).resolves.toBe(5);
|
|
174
|
+
});
|
|
175
|
+
it('passes args to count', async () => {
|
|
176
|
+
const { repo, delegate } = buildRepo();
|
|
177
|
+
delegate.count.mockResolvedValue(2);
|
|
178
|
+
const args = { where: { name: 'Alice' } };
|
|
179
|
+
await expect(repo.count(args)).resolves.toBe(2);
|
|
180
|
+
expect(delegate.count).toHaveBeenCalledWith(args);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
describe('prismaClient / modelDelegate getters', () => {
|
|
184
|
+
it('prismaClient returns the prisma instance', () => {
|
|
185
|
+
const { repo } = buildRepo();
|
|
186
|
+
expect(repo.prismaClient).toBeDefined();
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
describe('handleError()', () => {
|
|
190
|
+
it('throws unique constraint error for P2002 with target', () => {
|
|
191
|
+
const { repo } = buildRepo();
|
|
192
|
+
const err = new library_1.PrismaClientKnownRequestError('unique', {
|
|
193
|
+
code: 'P2002',
|
|
194
|
+
meta: { target: ['email', 'username'] },
|
|
195
|
+
});
|
|
196
|
+
expect(() => repo.testHandleError(err)).toThrow('Unique constraint violation on fields: email, username');
|
|
197
|
+
});
|
|
198
|
+
it('throws unique constraint error for P2002 without target', () => {
|
|
199
|
+
const { repo } = buildRepo();
|
|
200
|
+
const err = new library_1.PrismaClientKnownRequestError('unique', { code: 'P2002' });
|
|
201
|
+
expect(() => repo.testHandleError(err)).toThrow('Unique constraint violation on field');
|
|
202
|
+
});
|
|
203
|
+
it('throws not found error for P2025', () => {
|
|
204
|
+
const { repo } = buildRepo();
|
|
205
|
+
const err = new library_1.PrismaClientKnownRequestError('not found', { code: 'P2025' });
|
|
206
|
+
expect(() => repo.testHandleError(err)).toThrow('Record not found');
|
|
207
|
+
});
|
|
208
|
+
it('throws foreign key error for P2003', () => {
|
|
209
|
+
const { repo } = buildRepo();
|
|
210
|
+
const err = new library_1.PrismaClientKnownRequestError('fk', { code: 'P2003' });
|
|
211
|
+
expect(() => repo.testHandleError(err)).toThrow('Foreign key constraint violation');
|
|
212
|
+
});
|
|
213
|
+
it('throws generic db error for unknown prisma code', () => {
|
|
214
|
+
const { repo } = buildRepo();
|
|
215
|
+
const err = new library_1.PrismaClientKnownRequestError('unknown', { code: 'P9999' });
|
|
216
|
+
expect(() => repo.testHandleError(err)).toThrow('Database error:');
|
|
217
|
+
});
|
|
218
|
+
it('throws wrapped error for non-prisma errors', () => {
|
|
219
|
+
const { repo } = buildRepo();
|
|
220
|
+
expect(() => repo.testHandleError(new Error('generic error'))).toThrow('Database error: generic error');
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
// ─── Repository decorator ─────────────────────────────────────────────────────
|
|
225
|
+
describe('@Repository decorator', () => {
|
|
226
|
+
it('sets hazel:repository metadata with string shorthand', () => {
|
|
227
|
+
let UserRepo = class UserRepo {
|
|
228
|
+
};
|
|
229
|
+
UserRepo = __decorate([
|
|
230
|
+
(0, repository_decorator_1.Repository)('user')
|
|
231
|
+
], UserRepo);
|
|
232
|
+
const meta = Reflect.getMetadata('hazel:repository', UserRepo);
|
|
233
|
+
expect(meta).toEqual({ model: 'user' });
|
|
234
|
+
});
|
|
235
|
+
it('sets hazel:repository metadata with options object', () => {
|
|
236
|
+
let PostRepo = class PostRepo {
|
|
237
|
+
};
|
|
238
|
+
PostRepo = __decorate([
|
|
239
|
+
(0, repository_decorator_1.Repository)({ model: 'post' })
|
|
240
|
+
], PostRepo);
|
|
241
|
+
const meta = Reflect.getMetadata('hazel:repository', PostRepo);
|
|
242
|
+
expect(meta).toEqual({ model: 'post' });
|
|
243
|
+
});
|
|
244
|
+
it('sets hazel:injectable metadata', () => {
|
|
245
|
+
let CommentRepo = class CommentRepo {
|
|
246
|
+
};
|
|
247
|
+
CommentRepo = __decorate([
|
|
248
|
+
(0, repository_decorator_1.Repository)('comment')
|
|
249
|
+
], CommentRepo);
|
|
250
|
+
const injectable = Reflect.getMetadata('hazel:injectable', CommentRepo);
|
|
251
|
+
expect(injectable).toEqual({});
|
|
252
|
+
});
|
|
253
|
+
it('sets hazel:scope metadata when scope is provided', () => {
|
|
254
|
+
let SessionRepo = class SessionRepo {
|
|
255
|
+
};
|
|
256
|
+
SessionRepo = __decorate([
|
|
257
|
+
(0, repository_decorator_1.Repository)({ model: 'session', scope: 'REQUEST' })
|
|
258
|
+
], SessionRepo);
|
|
259
|
+
const scope = Reflect.getMetadata('hazel:scope', SessionRepo);
|
|
260
|
+
expect(scope).toBe('REQUEST');
|
|
261
|
+
});
|
|
262
|
+
it('sets hazel:injectable metadata with scope when scope is provided', () => {
|
|
263
|
+
let LogRepo = class LogRepo {
|
|
264
|
+
};
|
|
265
|
+
LogRepo = __decorate([
|
|
266
|
+
(0, repository_decorator_1.Repository)({ model: 'log', scope: 'TRANSIENT' })
|
|
267
|
+
], LogRepo);
|
|
268
|
+
const injectable = Reflect.getMetadata('hazel:injectable', LogRepo);
|
|
269
|
+
expect(injectable).toEqual({ scope: 'TRANSIENT' });
|
|
270
|
+
});
|
|
271
|
+
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RepositoryOptions } from '@hazeljs/core';
|
|
2
2
|
import 'reflect-metadata';
|
|
3
|
-
export declare function Repository(options: RepositoryOptions): ClassDecorator;
|
|
3
|
+
export declare function Repository(options: RepositoryOptions | string): ClassDecorator;
|
|
4
4
|
export declare function InjectRepository(): ParameterDecorator;
|
|
5
5
|
//# sourceMappingURL=repository.decorator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repository.decorator.d.ts","sourceRoot":"","sources":["../src/repository.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,kBAAkB,CAAC;AAE1B,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,
|
|
1
|
+
{"version":3,"file":"repository.decorator.d.ts","sourceRoot":"","sources":["../src/repository.decorator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,kBAAkB,CAAC;AAE1B,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,GAAG,cAAc,CAW9E;AAED,wBAAgB,gBAAgB,IAAI,kBAAkB,CA0BrD"}
|
|
@@ -5,7 +5,14 @@ exports.InjectRepository = InjectRepository;
|
|
|
5
5
|
require("reflect-metadata");
|
|
6
6
|
function Repository(options) {
|
|
7
7
|
return function (target) {
|
|
8
|
-
|
|
8
|
+
const opts = typeof options === 'string' ? { model: options } : options;
|
|
9
|
+
Reflect.defineMetadata('hazel:repository', opts, target);
|
|
10
|
+
// Implicitly mark the class as injectable — @Injectable() is not needed separately.
|
|
11
|
+
// Write metadata directly to avoid the ClassDecorator `Function` type constraint.
|
|
12
|
+
Reflect.defineMetadata('hazel:injectable', opts.scope ? { scope: opts.scope } : {}, target);
|
|
13
|
+
if (opts.scope) {
|
|
14
|
+
Reflect.defineMetadata('hazel:scope', opts.scope, target);
|
|
15
|
+
}
|
|
9
16
|
};
|
|
10
17
|
}
|
|
11
18
|
function InjectRepository() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hazeljs/prisma",
|
|
3
|
-
"version": "0.2.0-beta.
|
|
3
|
+
"version": "0.2.0-beta.81",
|
|
4
4
|
"description": "Prisma ORM integration for HazelJS framework",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -15,7 +15,6 @@
|
|
|
15
15
|
"clean": "rm -rf dist"
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@hazeljs/core": "^0.2.0-beta.8",
|
|
19
18
|
"@prisma/client": "^6.8.2"
|
|
20
19
|
},
|
|
21
20
|
"devDependencies": {
|
|
@@ -42,7 +41,14 @@
|
|
|
42
41
|
"orm",
|
|
43
42
|
"database"
|
|
44
43
|
],
|
|
45
|
-
"author": "Muhammad Arslan <
|
|
46
|
-
"license": "
|
|
47
|
-
"
|
|
44
|
+
"author": "Muhammad Arslan <muhammad.arslan@hazeljs.com>",
|
|
45
|
+
"license": "Apache-2.0",
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://github.com/hazeljs/hazel-js/issues"
|
|
48
|
+
},
|
|
49
|
+
"homepage": "https://hazeljs.com",
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@hazeljs/core": ">=0.2.0-beta.0"
|
|
52
|
+
},
|
|
53
|
+
"gitHead": "1054f957451360f973469d436a1d58e57cc9231a"
|
|
48
54
|
}
|