@groundbrick/service-base 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -512
- package/dist/core/BaseService.d.ts +7 -0
- package/dist/core/BaseService.d.ts.map +1 -1
- package/dist/core/BaseService.js +21 -6
- package/dist/core/BaseService.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/types/ServiceResult.d.ts +11 -0
- package/dist/types/ServiceResult.d.ts.map +1 -1
- package/dist/types/ServiceResult.js +102 -21
- package/dist/types/ServiceResult.js.map +1 -1
- package/package.json +14 -12
package/README.md
CHANGED
|
@@ -1,36 +1,6 @@
|
|
|
1
1
|
# @groundbrick/service-base
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
Service layer base classes and utilities for business logic implementation in layered architecture applications.
|
|
7
|
-
|
|
8
|
-
## 🚀 Features
|
|
9
|
-
|
|
10
|
-
### 🎯 **BaseService Class**
|
|
11
|
-
- Integrated logging with service context
|
|
12
|
-
- Database transaction management
|
|
13
|
-
- Input validation framework
|
|
14
|
-
- Standardized error handling
|
|
15
|
-
- Repository integration patterns
|
|
16
|
-
|
|
17
|
-
### 🔧 **Business Logic Patterns**
|
|
18
|
-
- Input validation before repository calls
|
|
19
|
-
- Business rule enforcement
|
|
20
|
-
- Cross-entity operations coordination
|
|
21
|
-
- Response transformation and mapping
|
|
22
|
-
|
|
23
|
-
### ⚡ **Error Handling**
|
|
24
|
-
- Business-specific error types (`BusinessError`)
|
|
25
|
-
- Validation error aggregation
|
|
26
|
-
- Repository error transformation
|
|
27
|
-
- Structured error responses for APIs
|
|
28
|
-
|
|
29
|
-
### ✅ **Validation System**
|
|
30
|
-
- Simple, extensible validation framework
|
|
31
|
-
- Common validation rules included
|
|
32
|
-
- Custom rule registration
|
|
33
|
-
- Field-level error reporting
|
|
3
|
+
Service layer base classes and utilities: validation, logging, error handling, result objects and transactions.
|
|
34
4
|
|
|
35
5
|
## Installation
|
|
36
6
|
|
|
@@ -38,11 +8,13 @@ Service layer base classes and utilities for business logic implementation in la
|
|
|
38
8
|
npm install @groundbrick/service-base
|
|
39
9
|
```
|
|
40
10
|
|
|
41
|
-
|
|
11
|
+
Depends on `@groundbrick/logger` (logging) and `@groundbrick/db-core` (database interfaces).
|
|
12
|
+
|
|
13
|
+
## Exports
|
|
42
14
|
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
-
|
|
15
|
+
- Classes: `BaseService`, `BusinessError`, `Validator`, `ValidationHelper`
|
|
16
|
+
- Functions: `createSuccessResult`, `createErrorResult`, `handleRepositoryError`
|
|
17
|
+
- Types: `ServiceOptions`, `ServiceResult`, `ValidationRule`, `ValidationRules`, `ValidationResult`
|
|
46
18
|
|
|
47
19
|
## Quick Start
|
|
48
20
|
|
|
@@ -56,7 +28,6 @@ interface User {
|
|
|
56
28
|
id: number;
|
|
57
29
|
name: string;
|
|
58
30
|
email: string;
|
|
59
|
-
active: boolean;
|
|
60
31
|
}
|
|
61
32
|
|
|
62
33
|
interface CreateUserRequest {
|
|
@@ -73,7 +44,6 @@ export class UserService extends BaseService {
|
|
|
73
44
|
const endTimer = this.startOperation('createUser');
|
|
74
45
|
|
|
75
46
|
try {
|
|
76
|
-
// 1. Validate input
|
|
77
47
|
const validationResult = await this.validate(userData, {
|
|
78
48
|
name: [
|
|
79
49
|
ValidationHelper.required(),
|
|
@@ -95,32 +65,11 @@ export class UserService extends BaseService {
|
|
|
95
65
|
);
|
|
96
66
|
}
|
|
97
67
|
|
|
98
|
-
|
|
99
|
-
const existingUser = await this.userRepository.findByEmail(userData.email);
|
|
100
|
-
if (existingUser) {
|
|
101
|
-
throw new BusinessError(
|
|
102
|
-
'User already exists',
|
|
103
|
-
'USER_EXISTS',
|
|
104
|
-
undefined,
|
|
105
|
-
{ email: userData.email }
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// 3. Create user
|
|
110
|
-
const user = await this.userRepository.create({
|
|
111
|
-
name: userData.name,
|
|
112
|
-
email: userData.email.toLowerCase(),
|
|
113
|
-
active: true
|
|
114
|
-
});
|
|
115
|
-
|
|
68
|
+
const user = await this.userRepository.create(userData);
|
|
116
69
|
this.logger.info('User created successfully', { userId: user.id });
|
|
117
70
|
return user;
|
|
118
|
-
|
|
119
71
|
} catch (error) {
|
|
120
|
-
|
|
121
|
-
throw error;
|
|
122
|
-
}
|
|
123
|
-
throw this.handleRepositoryError(error as Error);
|
|
72
|
+
throw this.handleRepositoryError(error);
|
|
124
73
|
} finally {
|
|
125
74
|
endTimer();
|
|
126
75
|
}
|
|
@@ -131,25 +80,24 @@ export class UserService extends BaseService {
|
|
|
131
80
|
### 2. Using Transactions
|
|
132
81
|
|
|
133
82
|
```typescript
|
|
83
|
+
import { BaseService, ServiceOptions } from '@groundbrick/service-base';
|
|
84
|
+
|
|
134
85
|
export class OrderService extends BaseService {
|
|
135
86
|
constructor(
|
|
136
87
|
private orderRepository: OrderRepository,
|
|
137
88
|
private inventoryRepository: InventoryRepository,
|
|
138
|
-
options
|
|
89
|
+
options: ServiceOptions
|
|
139
90
|
) {
|
|
140
91
|
super(options);
|
|
141
92
|
}
|
|
142
93
|
|
|
143
94
|
async createOrder(orderData: CreateOrderRequest): Promise<Order> {
|
|
144
|
-
// Use transaction for multi-repository operations
|
|
145
95
|
return await this.withTransaction(async (tx) => {
|
|
146
|
-
// Create order
|
|
147
96
|
const order = await this.orderRepository.createWithTransaction(tx, {
|
|
148
97
|
user_id: orderData.user_id,
|
|
149
98
|
total_amount: orderData.total
|
|
150
99
|
});
|
|
151
100
|
|
|
152
|
-
// Update inventory
|
|
153
101
|
for (const item of orderData.items) {
|
|
154
102
|
await this.inventoryRepository.decrementStockWithTransaction(
|
|
155
103
|
tx,
|
|
@@ -162,209 +110,63 @@ export class OrderService extends BaseService {
|
|
|
162
110
|
});
|
|
163
111
|
}
|
|
164
112
|
}
|
|
165
|
-
```
|
|
166
|
-
|
|
167
|
-
#### 📋 Transaction pattern:
|
|
168
|
-
1. **Create Parent First, Use Generated ID**
|
|
169
|
-
|
|
170
|
-
```typescript
|
|
171
|
-
// Inside withTransaction callback
|
|
172
|
-
const newOrder = await this.orderRepository.createWithTransaction(tx, {
|
|
173
|
-
user_id: orderData.user_id,
|
|
174
|
-
total_amount: totalAmount,
|
|
175
|
-
status: 'pending'
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
// newOrder.id is now available (auto-generated by database)
|
|
179
|
-
|
|
180
|
-
// Use the order ID for child records
|
|
181
|
-
for (const item of orderData.items) {
|
|
182
|
-
await this.orderItemRepository.createWithTransaction(tx, {
|
|
183
|
-
order_id: newOrder.id, // 👈 Use the generated ID
|
|
184
|
-
product_id: item.product_id,
|
|
185
|
-
quantity: item.quantity,
|
|
186
|
-
unit_price: item.unit_price
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
2. **Alternative: Bulk Creation**
|
|
192
|
-
```typescript
|
|
193
|
-
// Create all order items at once
|
|
194
|
-
const orderItemsData = orderData.items.map(item => ({
|
|
195
|
-
order_id: newOrder.id, // Same ID for all items
|
|
196
|
-
product_id: item.product_id,
|
|
197
|
-
quantity: item.quantity,
|
|
198
|
-
unit_price: item.unit_price
|
|
199
|
-
}));
|
|
200
|
-
|
|
201
|
-
await this.orderItemRepository.createManyWithTransaction(tx, orderItemsData);
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
3. **Complete Example with Proper Flow**
|
|
205
|
-
```typescript
|
|
206
|
-
async createOrder(orderData: CreateOrderRequest): Promise<Order> {
|
|
207
|
-
return await this.withTransaction(async (tx) => {
|
|
208
|
-
// 1. Validate business rules first
|
|
209
|
-
await this.validateOrderData(orderData);
|
|
210
|
-
|
|
211
|
-
// 2. Calculate total amount
|
|
212
|
-
let totalAmount = 0;
|
|
213
|
-
const validatedItems = [];
|
|
214
|
-
|
|
215
|
-
for (const item of orderData.items) {
|
|
216
|
-
const product = await this.productRepository.findByIdWithTransaction(tx, item.product_id);
|
|
217
|
-
// ... validation logic
|
|
218
|
-
totalAmount += product.price * item.quantity;
|
|
219
|
-
validatedItems.push({
|
|
220
|
-
product_id: item.product_id,
|
|
221
|
-
quantity: item.quantity,
|
|
222
|
-
unit_price: product.price
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// 3. Create the order (gets auto-generated ID)
|
|
227
|
-
const newOrder = await this.orderRepository.createWithTransaction(tx, {
|
|
228
|
-
user_id: orderData.user_id,
|
|
229
|
-
total_amount: totalAmount,
|
|
230
|
-
status: 'pending',
|
|
231
|
-
created_at: new Date()
|
|
232
|
-
});
|
|
233
113
|
|
|
234
|
-
|
|
235
|
-
for (const item of validatedItems) {
|
|
236
|
-
await this.orderItemRepository.createWithTransaction(tx, {
|
|
237
|
-
order_id: newOrder.id, // 👈 Key: Use generated order ID
|
|
238
|
-
product_id: item.product_id,
|
|
239
|
-
quantity: item.quantity,
|
|
240
|
-
unit_price: item.unit_price
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// 5. Update product inventory
|
|
245
|
-
for (const item of orderData.items) {
|
|
246
|
-
await this.productRepository.decrementStockWithTransaction(
|
|
247
|
-
tx,
|
|
248
|
-
item.product_id,
|
|
249
|
-
item.quantity
|
|
250
|
-
);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// 6. Return the complete order (with ID)
|
|
254
|
-
return newOrder;
|
|
255
|
-
});
|
|
256
|
-
}
|
|
114
|
+
const orderService = new OrderService(orderRepository, inventoryRepository, { database });
|
|
257
115
|
```
|
|
258
116
|
|
|
259
|
-
|
|
260
|
-
Your repositories need to support transaction-aware methods:
|
|
261
|
-
```typescript
|
|
262
|
-
// In your OrderRepository
|
|
263
|
-
class OrderRepository extends BaseRepository<Order> {
|
|
264
|
-
async createWithTransaction(tx: DatabaseTransaction, data: Partial<Order>): Promise<Order> {
|
|
265
|
-
// Use tx.query() instead of this.db.query()
|
|
266
|
-
const result = await tx.query(
|
|
267
|
-
'INSERT INTO orders (user_id, total_amount, status, created_at) VALUES (?, ?, ?, ?) RETURNING *',
|
|
268
|
-
[data.user_id, data.total_amount, data.status, data.created_at]
|
|
269
|
-
);
|
|
270
|
-
return result.rows[0];
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// In your OrderItemRepository
|
|
275
|
-
class OrderItemRepository extends BaseRepository<OrderItem> {
|
|
276
|
-
async createWithTransaction(tx: DatabaseTransaction, data: Partial<OrderItem>): Promise<OrderItem> {
|
|
277
|
-
const result = await tx.query(
|
|
278
|
-
'INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?) RETURNING *',
|
|
279
|
-
[data.order_id, data.product_id, data.quantity, data.unit_price]
|
|
280
|
-
);
|
|
281
|
-
return result.rows[0];
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
async createManyWithTransaction(tx: DatabaseTransaction, items: Partial<OrderItem>[]): Promise<OrderItem[]> {
|
|
285
|
-
// Bulk insert implementation
|
|
286
|
-
const values = items.map(item => [item.order_id, item.product_id, item.quantity, item.unit_price]);
|
|
287
|
-
// ... bulk insert logic
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
```
|
|
291
|
-
#### 💡 Key Points:
|
|
292
|
-
|
|
293
|
-
- Order matters: Create parent record first to get the ID
|
|
294
|
-
- Use the transaction: All operations must use the same tx parameter
|
|
295
|
-
- ID is immediately available: After createWithTransaction, the returned object has the generated ID
|
|
296
|
-
- All-or-nothing: If any step fails, the entire transaction rolls back
|
|
297
|
-
- Performance: Consider bulk operations for multiple child records
|
|
117
|
+
Repository methods that take part in the transaction receive `tx` and run their queries with `tx.query(sql, params)`. If the callback throws, the database client rolls the transaction back.
|
|
298
118
|
|
|
299
119
|
### 3. Custom Validation Rules
|
|
300
120
|
|
|
301
121
|
```typescript
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
// Register custom validation rules
|
|
307
|
-
this.validator.registerRule('sku', (value) => {
|
|
308
|
-
const skuPattern = /^[A-Z]{2}-\d{4}$/;
|
|
309
|
-
return skuPattern.test(value) ? null : 'SKU must follow format: XX-0000';
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
async createProduct(productData: CreateProductRequest): Promise<Product> {
|
|
314
|
-
const validationResult = await this.validate(productData, {
|
|
315
|
-
name: [ValidationHelper.required(), ValidationHelper.minLength(2)],
|
|
316
|
-
sku: [ValidationHelper.required(), this.validator.getRule('sku')!],
|
|
317
|
-
price: [ValidationHelper.required(), ValidationHelper.numberRange(0.01, 10000)]
|
|
318
|
-
});
|
|
319
|
-
|
|
320
|
-
if (!validationResult.isValid) {
|
|
321
|
-
throw new BusinessError('Invalid product data', 'VALIDATION_FAILED', undefined, {
|
|
322
|
-
errors: validationResult.errors
|
|
323
|
-
});
|
|
324
|
-
}
|
|
122
|
+
this.validator.registerRule('sku', (value) => {
|
|
123
|
+
const skuPattern = /^[A-Z]{2}-\d{4}$/;
|
|
124
|
+
return skuPattern.test(value) ? null : 'SKU must follow format: XX-0000';
|
|
125
|
+
});
|
|
325
126
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
127
|
+
const result = await this.validate(productData, {
|
|
128
|
+
name: [ValidationHelper.required(), ValidationHelper.minLength(2)],
|
|
129
|
+
sku: [ValidationHelper.required(), this.validator.getRule('sku')!],
|
|
130
|
+
price: [ValidationHelper.required(), ValidationHelper.numberRange(0.01, 10000)]
|
|
131
|
+
});
|
|
329
132
|
```
|
|
330
133
|
|
|
331
134
|
## API Reference
|
|
332
135
|
|
|
333
136
|
### BaseService
|
|
334
137
|
|
|
335
|
-
The abstract base class that your services should extend.
|
|
336
|
-
|
|
337
138
|
#### Constructor Options
|
|
338
139
|
|
|
339
140
|
```typescript
|
|
340
141
|
interface ServiceOptions {
|
|
341
142
|
database?: DatabaseClient; // For transaction support
|
|
342
143
|
validator?: Validator; // Custom validator instance
|
|
343
|
-
config?: Record<string, any>; // Service-specific config
|
|
144
|
+
config?: Record<string, any>; // Service-specific config (not read by BaseService)
|
|
344
145
|
}
|
|
345
146
|
```
|
|
346
147
|
|
|
347
|
-
#### Protected
|
|
148
|
+
#### Protected Members
|
|
348
149
|
|
|
349
150
|
```typescript
|
|
350
|
-
//
|
|
151
|
+
protected readonly logger: Logger // child logger with context "service"
|
|
152
|
+
protected readonly db?: DatabaseClient
|
|
153
|
+
protected readonly validator: Validator
|
|
154
|
+
|
|
351
155
|
protected async validate<T>(data: T, rules: ValidationRules): Promise<ValidationResult>
|
|
352
156
|
protected validateRequired(data: Record<string, any>, fields: string[]): void
|
|
353
|
-
|
|
354
|
-
// Transactions
|
|
355
157
|
protected async withTransaction<T>(callback: (tx: DatabaseTransaction) => Promise<T>): Promise<T>
|
|
356
|
-
|
|
357
|
-
// Error Handling
|
|
358
|
-
protected handleRepositoryError(error: Error): BusinessError
|
|
359
|
-
|
|
360
|
-
// Utilities
|
|
158
|
+
protected handleRepositoryError(error: unknown): BusinessError
|
|
361
159
|
protected startOperation(operation: string, metadata?: Record<string, any>): () => void
|
|
362
160
|
protected safeSerialize(obj: any): any
|
|
363
161
|
```
|
|
364
162
|
|
|
365
|
-
|
|
163
|
+
- `validate` returns the errors without throwing. A rule that throws results in `BusinessError` with code `VALIDATION_ERROR`.
|
|
164
|
+
- `validateRequired` throws `BusinessError` with code `MISSING_REQUIRED_FIELDS` and `context.missingFields` when a field is `undefined`, `null` or `''`.
|
|
165
|
+
- `withTransaction` throws `BusinessError` with code `NO_DATABASE` without a database. An `Error` thrown by the callback is rethrown untouched; anything else goes through `handleRepositoryError`. Business errors are logged at debug level, others at error level.
|
|
166
|
+
- `startOperation` returns a function that ends the timer.
|
|
167
|
+
- `safeSerialize` returns a JSON copy, or `{ error }` when the object cannot be serialized.
|
|
366
168
|
|
|
367
|
-
|
|
169
|
+
### BusinessError
|
|
368
170
|
|
|
369
171
|
```typescript
|
|
370
172
|
class BusinessError extends Error {
|
|
@@ -375,13 +177,11 @@ class BusinessError extends Error {
|
|
|
375
177
|
context?: Record<string, any>
|
|
376
178
|
)
|
|
377
179
|
|
|
378
|
-
// Properties
|
|
379
180
|
readonly code: string
|
|
380
181
|
readonly originalError?: Error
|
|
381
182
|
readonly context?: Record<string, any>
|
|
382
183
|
readonly timestamp: Date
|
|
383
184
|
|
|
384
|
-
// Methods
|
|
385
185
|
toJSON(): Record<string, any>
|
|
386
186
|
toUserResponse(): { error: string; code: string; timestamp: string }
|
|
387
187
|
hasCode(code: string): boolean
|
|
@@ -389,325 +189,117 @@ class BusinessError extends Error {
|
|
|
389
189
|
}
|
|
390
190
|
```
|
|
391
191
|
|
|
392
|
-
|
|
192
|
+
`toJSON` includes the stack and the context; `toUserResponse` does not.
|
|
393
193
|
|
|
394
|
-
|
|
194
|
+
### ServiceResult
|
|
395
195
|
|
|
396
196
|
```typescript
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
static email(): ValidationRule
|
|
403
|
-
static numberRange(min?: number, max?: number): ValidationRule
|
|
404
|
-
static pattern(regex: RegExp, message: string): ValidationRule
|
|
405
|
-
static oneOf(options: any[], message?: string): ValidationRule
|
|
406
|
-
|
|
407
|
-
// Array rules
|
|
408
|
-
static arrayMinLength(min: number): ValidationRule
|
|
409
|
-
|
|
410
|
-
// Advanced rules
|
|
411
|
-
static custom(validator: (value: any, data?: any) => string | null): ValidationRule
|
|
412
|
-
static when(condition: (data: any) => boolean, rule: ValidationRule): ValidationRule
|
|
413
|
-
|
|
414
|
-
// Utility methods
|
|
415
|
-
static combine(...rules: ValidationRule[]): ValidationRule[]
|
|
416
|
-
static entityId(): ValidationRule[]
|
|
417
|
-
|
|
418
|
-
// Pre-configured rule sets
|
|
419
|
-
static userCreation(): ValidationRules
|
|
420
|
-
static pagination(): ValidationRules
|
|
421
|
-
}
|
|
422
|
-
```
|
|
423
|
-
|
|
424
|
-
## ✅ Validation System
|
|
425
|
-
|
|
426
|
-
### Basic Validation
|
|
427
|
-
|
|
428
|
-
```typescript
|
|
429
|
-
const result = await this.validate(data, {
|
|
430
|
-
email: [ValidationHelper.required(), ValidationHelper.email()],
|
|
431
|
-
age: [ValidationHelper.numberRange(18, 120)]
|
|
432
|
-
});
|
|
433
|
-
|
|
434
|
-
if (!result.isValid) {
|
|
435
|
-
// Handle validation errors
|
|
436
|
-
console.log(result.errors); // { email: ['Must be a valid email'], age: ['Must be at least 18'] }
|
|
197
|
+
interface ServiceResult<T = any> {
|
|
198
|
+
success: boolean;
|
|
199
|
+
data?: T;
|
|
200
|
+
error?: { message: string; code: string; details?: Record<string, any> };
|
|
201
|
+
metadata?: { duration?: number; timestamp: string; operation?: string };
|
|
437
202
|
}
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
### 🧠 Custom Validation Rules
|
|
441
|
-
|
|
442
|
-
```typescript
|
|
443
|
-
// Register a custom rule
|
|
444
|
-
this.validator.registerRule('phone', (value) => {
|
|
445
|
-
const phonePattern = /^\+?[\d\s-()]{10,}$/;
|
|
446
|
-
return phonePattern.test(value) ? null : 'Invalid phone number format';
|
|
447
|
-
});
|
|
448
|
-
|
|
449
|
-
// Use in validation
|
|
450
|
-
const rules = {
|
|
451
|
-
phone: [ValidationHelper.required(), this.validator.getRule('phone')!]
|
|
452
|
-
};
|
|
453
|
-
```
|
|
454
|
-
|
|
455
|
-
### Conditional Validation
|
|
456
|
-
|
|
457
|
-
```typescript
|
|
458
|
-
const rules = {
|
|
459
|
-
email: [ValidationHelper.required(), ValidationHelper.email()],
|
|
460
|
-
password: ValidationHelper.when(
|
|
461
|
-
(data) => data.isNewUser === true,
|
|
462
|
-
ValidationHelper.combine(
|
|
463
|
-
ValidationHelper.required(),
|
|
464
|
-
ValidationHelper.minLength(8)
|
|
465
|
-
)
|
|
466
|
-
)
|
|
467
|
-
};
|
|
468
|
-
```
|
|
469
|
-
|
|
470
|
-
## Error Handling Patterns
|
|
471
|
-
|
|
472
|
-
### 1. Repository Error Transformation
|
|
473
203
|
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
```typescript
|
|
477
|
-
// Database constraint violation → BusinessError with DUPLICATE_RESOURCE code
|
|
478
|
-
// Record not found → BusinessError with RESOURCE_NOT_FOUND code
|
|
479
|
-
// Foreign key violation → BusinessError with CONSTRAINT_VIOLATION code
|
|
480
|
-
// Other errors → BusinessError with OPERATION_FAILED code
|
|
204
|
+
createSuccessResult<T>(data: T, metadata?: any): ServiceResult<T>
|
|
205
|
+
createErrorResult(error: BusinessError | Error | any): ServiceResult
|
|
481
206
|
```
|
|
482
207
|
|
|
483
|
-
|
|
208
|
+
`createErrorResult` passes the error through `handleRepositoryError`; `details` is the error's `context`.
|
|
484
209
|
|
|
485
210
|
```typescript
|
|
486
211
|
try {
|
|
487
212
|
const user = await userService.createUser(userData);
|
|
488
213
|
return createSuccessResult(user);
|
|
489
214
|
} catch (error) {
|
|
490
|
-
|
|
491
|
-
// Handle business logic errors
|
|
492
|
-
return createErrorResult(error);
|
|
493
|
-
}
|
|
494
|
-
// Handle unexpected errors
|
|
495
|
-
throw error;
|
|
496
|
-
}
|
|
497
|
-
```
|
|
498
|
-
|
|
499
|
-
### 3. API Integration
|
|
500
|
-
|
|
501
|
-
```typescript
|
|
502
|
-
export class UserController {
|
|
503
|
-
async createUser(req: any, res: any) {
|
|
504
|
-
try {
|
|
505
|
-
const user = await this.userService.createUser(req.body);
|
|
506
|
-
res.status(201).json(createSuccessResult(user));
|
|
507
|
-
} catch (error) {
|
|
508
|
-
const result = createErrorResult(error as Error);
|
|
509
|
-
|
|
510
|
-
// Map business error codes to HTTP status codes
|
|
511
|
-
let status = 500;
|
|
512
|
-
if (BusinessError.isBusinessError(error)) {
|
|
513
|
-
switch (error.code) {
|
|
514
|
-
case 'VALIDATION_FAILED': status = 400; break;
|
|
515
|
-
case 'USER_EXISTS': status = 409; break;
|
|
516
|
-
case 'USER_NOT_FOUND': status = 404; break;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
res.status(status).json(result);
|
|
521
|
-
}
|
|
522
|
-
}
|
|
215
|
+
return createErrorResult(error);
|
|
523
216
|
}
|
|
524
217
|
```
|
|
525
218
|
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
### Simple Transaction
|
|
219
|
+
### Validator
|
|
529
220
|
|
|
530
221
|
```typescript
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
// Update user
|
|
534
|
-
const user = await this.userRepository.updateWithTransaction(tx, userId, {
|
|
535
|
-
name: profileData.name,
|
|
536
|
-
email: profileData.email
|
|
537
|
-
});
|
|
222
|
+
type ValidationRule = (value: any, data?: any) => string | null;
|
|
223
|
+
type ValidationRules = Record<string, ValidationRule[]>;
|
|
538
224
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
});
|
|
544
|
-
|
|
545
|
-
return user;
|
|
546
|
-
});
|
|
225
|
+
interface ValidationResult {
|
|
226
|
+
isValid: boolean;
|
|
227
|
+
errors: Record<string, string[]>;
|
|
228
|
+
errorCount: number;
|
|
547
229
|
}
|
|
548
|
-
```
|
|
549
230
|
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
return await this.withTransaction(async (tx) => {
|
|
555
|
-
// 1. Validate inventory
|
|
556
|
-
for (const item of orderData.items) {
|
|
557
|
-
const product = await this.productRepository.findByIdWithTransaction(tx, item.productId);
|
|
558
|
-
if (product.stock < item.quantity) {
|
|
559
|
-
throw new BusinessError('Insufficient stock', 'INSUFFICIENT_STOCK');
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
// 2. Create order
|
|
564
|
-
const order = await this.orderRepository.createWithTransaction(tx, orderData);
|
|
565
|
-
|
|
566
|
-
// 3. Update inventory
|
|
567
|
-
for (const item of orderData.items) {
|
|
568
|
-
await this.productRepository.decrementStockWithTransaction(
|
|
569
|
-
tx, item.productId, item.quantity
|
|
570
|
-
);
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
// 4. Send notification (example of non-transactional side effect)
|
|
574
|
-
// Note: This should be handled outside the transaction
|
|
575
|
-
// Consider using event-driven patterns for side effects
|
|
576
|
-
|
|
577
|
-
return order;
|
|
578
|
-
});
|
|
231
|
+
class Validator {
|
|
232
|
+
registerRule(name: string, rule: ValidationRule): void
|
|
233
|
+
getRule(name: string): ValidationRule | undefined
|
|
234
|
+
validate<T>(data: T, rules: ValidationRules): Promise<ValidationResult>
|
|
579
235
|
}
|
|
580
236
|
```
|
|
581
237
|
|
|
582
|
-
|
|
238
|
+
All the rules of a field run, in order. Rules are synchronous and return an error message or `null`.
|
|
583
239
|
|
|
584
|
-
###
|
|
240
|
+
### ValidationHelper
|
|
585
241
|
|
|
586
242
|
```typescript
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
243
|
+
class ValidationHelper {
|
|
244
|
+
// Basic rules
|
|
245
|
+
static required(): ValidationRule
|
|
246
|
+
static minLength(min: number): ValidationRule
|
|
247
|
+
static maxLength(max: number): ValidationRule
|
|
248
|
+
static email(): ValidationRule
|
|
249
|
+
static numberRange(min?: number, max?: number): ValidationRule
|
|
250
|
+
static pattern(regex: RegExp, message: string): ValidationRule
|
|
251
|
+
static oneOf(options: any[], message?: string): ValidationRule
|
|
593
252
|
|
|
594
|
-
//
|
|
595
|
-
|
|
596
|
-
async createUser(userData: CreateUserRequest): Promise<User> { }
|
|
597
|
-
async sendWelcomeEmail(user: User): Promise<void> { } // Should be EmailService
|
|
598
|
-
async generateReport(userId: number): Promise<Report> { } // Should be ReportService
|
|
599
|
-
}
|
|
600
|
-
```
|
|
253
|
+
// Array rules
|
|
254
|
+
static arrayMinLength(min: number): ValidationRule
|
|
601
255
|
|
|
602
|
-
|
|
256
|
+
// Advanced rules
|
|
257
|
+
static custom(validator: (value: any, data?: any) => string | null): ValidationRule
|
|
258
|
+
static when(condition: (data: any) => boolean, rule: ValidationRule): ValidationRule
|
|
603
259
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
const validationResult = await this.validate(userData, this.getUserValidationRules());
|
|
608
|
-
if (!validationResult.isValid) {
|
|
609
|
-
throw new BusinessError('Validation failed', 'VALIDATION_FAILED', undefined, {
|
|
610
|
-
errors: validationResult.errors
|
|
611
|
-
});
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// Continue with business logic...
|
|
615
|
-
}
|
|
260
|
+
// Utility methods
|
|
261
|
+
static combine(...rules: ValidationRule[]): ValidationRule[]
|
|
262
|
+
static entityId(): ValidationRule[]
|
|
616
263
|
|
|
617
|
-
//
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
if (!userData.email) { // Too late for basic validation
|
|
621
|
-
throw new Error('Email required');
|
|
622
|
-
}
|
|
623
|
-
// ...
|
|
264
|
+
// Rule sets by field
|
|
265
|
+
static userCreation() // name, email, password
|
|
266
|
+
static pagination() // limit (1-100), offset (from 0)
|
|
624
267
|
}
|
|
625
268
|
```
|
|
626
269
|
|
|
627
|
-
|
|
270
|
+
String rules pass for values that are not strings, and `arrayMinLength` for values that are not arrays. `numberRange` and `oneOf` also check absent values.
|
|
628
271
|
|
|
629
272
|
```typescript
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
amount
|
|
639
|
-
});
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// ❌ Bad - No transaction, inconsistent state possible
|
|
644
|
-
async transferFunds(fromAccount: number, toAccount: number, amount: number): Promise<void> {
|
|
645
|
-
await this.accountRepository.decrementBalance(fromAccount, amount);
|
|
646
|
-
await this.accountRepository.incrementBalance(toAccount, amount); // Could fail, leaving inconsistent state
|
|
647
|
-
await this.transactionRepository.create({ from_account: fromAccount, to_account: toAccount, amount });
|
|
648
|
-
}
|
|
649
|
-
```
|
|
650
|
-
|
|
651
|
-
### 4. Handle Errors Appropriately
|
|
273
|
+
const result = await this.validate(data, {
|
|
274
|
+
email: [ValidationHelper.required(), ValidationHelper.email()],
|
|
275
|
+
age: [ValidationHelper.numberRange(18, 120)],
|
|
276
|
+
password: [
|
|
277
|
+
ValidationHelper.when((data) => data.isNewUser === true, ValidationHelper.required()),
|
|
278
|
+
ValidationHelper.minLength(8)
|
|
279
|
+
]
|
|
280
|
+
});
|
|
652
281
|
|
|
653
|
-
|
|
654
|
-
//
|
|
655
|
-
async getUserById(id: number): Promise<User> {
|
|
656
|
-
try {
|
|
657
|
-
this.validateRequired({ id }, ['id']);
|
|
658
|
-
|
|
659
|
-
const user = await this.userRepository.findById(id);
|
|
660
|
-
if (!user) {
|
|
661
|
-
throw new BusinessError('User not found', 'USER_NOT_FOUND', undefined, { userId: id });
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
return user;
|
|
665
|
-
} catch (error) {
|
|
666
|
-
if (BusinessError.isBusinessError(error)) {
|
|
667
|
-
throw error; // Re-throw business errors
|
|
668
|
-
}
|
|
669
|
-
// Transform repository errors
|
|
670
|
-
throw this.handleRepositoryError(error as Error);
|
|
671
|
-
}
|
|
282
|
+
if (!result.isValid) {
|
|
283
|
+
console.log(result.errors); // { email: ['Must be a valid email address'], age: ['Must be at least 18'] }
|
|
672
284
|
}
|
|
673
285
|
```
|
|
674
286
|
|
|
675
|
-
##
|
|
676
|
-
|
|
677
|
-
This service layer integrates seamlessly with other microframework packages:
|
|
287
|
+
## Repository Errors
|
|
678
288
|
|
|
679
|
-
|
|
680
|
-
import { createLogger } from '@groundbrick/logger';
|
|
681
|
-
import { DatabaseFactory } from '@groundbrick/db-postgres';
|
|
682
|
-
import { UserRepository } from '@groundbrick/repository-base';
|
|
683
|
-
import { UserService } from './UserService';
|
|
684
|
-
|
|
685
|
-
// Initialize database
|
|
686
|
-
const db = DatabaseFactory.getInstance({
|
|
687
|
-
host: 'localhost',
|
|
688
|
-
database: 'myapp',
|
|
689
|
-
user: 'user',
|
|
690
|
-
password: 'password'
|
|
691
|
-
});
|
|
289
|
+
`handleRepositoryError(error: unknown): BusinessError` returns a `BusinessError` as it is and converts anything else. The MySQL/MariaDB or PostgreSQL driver code is looked up first, through `cause`/`originalError`, then the message text.
|
|
692
290
|
|
|
693
|
-
|
|
694
|
-
|
|
291
|
+
| Code | Situation |
|
|
292
|
+
|---|---|
|
|
293
|
+
| `DUPLICATE_RESOURCE` | Unique constraint violation |
|
|
294
|
+
| `CONSTRAINT_VIOLATION` | Referenced row missing, or check/exclusion violation |
|
|
295
|
+
| `RESOURCE_IN_USE` | Row still referenced by others |
|
|
296
|
+
| `INVALID_VALUE` | Null, too long, out of range or badly formatted value |
|
|
297
|
+
| `DATABASE_TIMEOUT` | Deadlock, lock wait or query timeout |
|
|
298
|
+
| `QUERY_ERROR` | Any other `QueryError` of `@groundbrick/db-core` |
|
|
299
|
+
| `OPERATION_FAILED` | Any other error |
|
|
695
300
|
|
|
696
|
-
|
|
697
|
-
const userService = new UserService(userRepository, { database: db });
|
|
301
|
+
The messages are in Portuguese and the original error is in `originalError`.
|
|
698
302
|
|
|
699
|
-
|
|
700
|
-
const user = await userService.createUser({
|
|
701
|
-
name: 'John Doe',
|
|
702
|
-
email: 'john@example.com'
|
|
703
|
-
});
|
|
704
|
-
```
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
## 📜 License
|
|
303
|
+
## License
|
|
708
304
|
|
|
709
305
|
MIT
|
|
710
|
-
|
|
711
|
-
---
|
|
712
|
-
|
|
713
|
-
|
|
@@ -3,6 +3,7 @@ import { DatabaseTransaction, DatabaseClient } from '@groundbrick/db-core';
|
|
|
3
3
|
import { ServiceOptions } from '../types/ServiceOptions.js';
|
|
4
4
|
import { ValidationRules, Validator } from '../validation/Validator.js';
|
|
5
5
|
import { ValidationResult } from '../validation/ValidationResult.js';
|
|
6
|
+
import { BusinessError } from '../types/BusinessError.js';
|
|
6
7
|
/**
|
|
7
8
|
* Abstract base service class providing common service layer functionality
|
|
8
9
|
*
|
|
@@ -31,6 +32,12 @@ export declare abstract class BaseService {
|
|
|
31
32
|
* @returns Promise with callback result
|
|
32
33
|
*/
|
|
33
34
|
protected withTransaction<T>(callback: (tx: DatabaseTransaction) => Promise<T>): Promise<T>;
|
|
35
|
+
/**
|
|
36
|
+
* Transform repository errors into business errors
|
|
37
|
+
* @param error - Original error from repository layer
|
|
38
|
+
* @returns BusinessError with appropriate context
|
|
39
|
+
*/
|
|
40
|
+
protected handleRepositoryError(error: unknown): BusinessError;
|
|
34
41
|
/**
|
|
35
42
|
* Validate required fields are present and not empty
|
|
36
43
|
* @param data - Object to check
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseService.d.ts","sourceRoot":"","sources":["../../src/core/BaseService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAgB,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"BaseService.d.ts","sourceRoot":"","sources":["../../src/core/BaseService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAgB,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG1D;;;;;;;;;GASG;AACH,8BAAsB,WAAW;IAC7B,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAClC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,cAAc,CAAC;IACvC,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;gBAE5B,OAAO,CAAC,EAAE,cAAc;IAWpC;;;;;OAKG;cACa,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAoBvF;;;;OAIG;cACa,eAAe,CAAC,CAAC,EAC7B,QAAQ,EAAE,CAAC,EAAE,EAAE,mBAAmB,KAAK,OAAO,CAAC,CAAC,CAAC,GAClD,OAAO,CAAC,CAAC,CAAC;IAsCb;;;;OAIG;IACH,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa;IAI9D;;;;;OAKG;IACH,SAAS,CAAC,gBAAgB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAmB7E;;;;;OAKG;IACH,SAAS,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,IAAI;IAKvF;;;;OAIG;IACH,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG;CAOzC"}
|
package/dist/core/BaseService.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createLogger } from '@groundbrick/logger';
|
|
2
2
|
import { Validator } from '../validation/Validator.js';
|
|
3
3
|
import { BusinessError } from '../types/BusinessError.js';
|
|
4
|
-
import {
|
|
4
|
+
import { handleRepositoryError } from '../types/ServiceResult.js';
|
|
5
5
|
/**
|
|
6
6
|
* Abstract base service class providing common service layer functionality
|
|
7
7
|
*
|
|
@@ -60,14 +60,14 @@ export class BaseService {
|
|
|
60
60
|
const transactionId = Math.random().toString(36).substring(7);
|
|
61
61
|
this.logger.debug('Starting transaction', {
|
|
62
62
|
transactionId,
|
|
63
|
-
dbType: this.db.getDatabaseType()
|
|
63
|
+
dbType: this.db.getDatabaseType()
|
|
64
64
|
});
|
|
65
65
|
try {
|
|
66
|
-
//
|
|
66
|
+
// The database client commits or rolls back
|
|
67
67
|
const result = await this.db.transaction(async (transaction) => {
|
|
68
68
|
this.logger.debug('Transaction started successfully', {
|
|
69
69
|
transactionId,
|
|
70
|
-
dbType: transaction.getDatabaseType()
|
|
70
|
+
dbType: transaction.getDatabaseType()
|
|
71
71
|
});
|
|
72
72
|
return await callback(transaction);
|
|
73
73
|
});
|
|
@@ -75,10 +75,25 @@ export class BaseService {
|
|
|
75
75
|
return result;
|
|
76
76
|
}
|
|
77
77
|
catch (error) {
|
|
78
|
-
|
|
79
|
-
|
|
78
|
+
if (BusinessError.isBusinessError(error)) {
|
|
79
|
+
// A business rule aborted the unit of work (e.g. NOT_FOUND)
|
|
80
|
+
this.logger.debug('Transaction aborted', { transactionId, code: error.code });
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
this.logger.error('Transaction failed', error instanceof Error ? error : new Error(String(error)), { transactionId });
|
|
84
|
+
}
|
|
85
|
+
// Rethrows an Error untouched; a non-Error throw is mapped to a BusinessError.
|
|
86
|
+
throw error instanceof Error ? error : this.handleRepositoryError(error);
|
|
80
87
|
}
|
|
81
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* Transform repository errors into business errors
|
|
91
|
+
* @param error - Original error from repository layer
|
|
92
|
+
* @returns BusinessError with appropriate context
|
|
93
|
+
*/
|
|
94
|
+
handleRepositoryError(error) {
|
|
95
|
+
return handleRepositoryError(error);
|
|
96
|
+
}
|
|
82
97
|
/**
|
|
83
98
|
* Validate required fields are present and not empty
|
|
84
99
|
* @param data - Object to check
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseService.js","sourceRoot":"","sources":["../../src/core/BaseService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAG3D,OAAO,EAAmB,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAExE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"BaseService.js","sourceRoot":"","sources":["../../src/core/BaseService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAG3D,OAAO,EAAmB,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAExE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAElE;;;;;;;;;GASG;AACH,MAAM,OAAgB,WAAW;IACV,MAAM,CAAS;IACf,EAAE,CAAkB;IACpB,SAAS,CAAY;IAExC,YAAY,OAAwB;QAChC,IAAI,CAAC,MAAM,GAAG,YAAY,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,QAAQ,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,IAAI,SAAS,EAAE,CAAC;QAEvD,wDAAwD;QACxD,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;YAC1C,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,eAAe,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACpE,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,QAAQ,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AED;;;;;OAKG;IACO,gBAAgB,CAAC,IAAyB,EAAE,MAAgB;QAClE,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;gBAC1E,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACxB,CAAC;QACL,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,aAAa,CACnB,4BAA4B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAChD,yBAAyB,EACzB,SAAS,EACT,EAAE,aAAa,EAAE,OAAO,EAAE,CAC7B,CAAC;QACN,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACO,cAAc,CAAC,SAAiB,EAAE,QAA8B;QACtE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,SAAS,EAAE,EAAE,QAAQ,CAAC,CAAC;QACrD,OAAO,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,SAAS,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED;;;;OAIG;IACO,aAAa,CAAC,GAAQ;QAC5B,IAAI,CAAC;YACD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3C,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,EAAE,KAAK,EAAE,4BAA4B,EAAE,CAAC;QACnD,CAAC;IACL,CAAC;CACJ"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { BaseService } from './core/BaseService.js';
|
|
2
2
|
export { BusinessError } from './types/BusinessError.js';
|
|
3
3
|
export type { ServiceResult } from './types/ServiceResult.js';
|
|
4
|
-
export { createSuccessResult, createErrorResult } from './types/ServiceResult.js';
|
|
4
|
+
export { createSuccessResult, createErrorResult, handleRepositoryError } from './types/ServiceResult.js';
|
|
5
5
|
export { Validator } from './validation/Validator.js';
|
|
6
6
|
export { ValidationHelper } from './validation/ValidationHelper.js';
|
|
7
7
|
export type { ValidationRule, ValidationRules } from './validation/Validator.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAMpD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAMzG,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,YAAY,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AACjF,YAAY,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAMzE,YAAY,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// packages/service-base/src/index.ts
|
|
2
1
|
// ============================================================================
|
|
3
2
|
// CORE CLASSES
|
|
4
3
|
// ============================================================================
|
|
@@ -7,7 +6,7 @@ export { BaseService } from './core/BaseService.js';
|
|
|
7
6
|
// ERROR HANDLING
|
|
8
7
|
// ============================================================================
|
|
9
8
|
export { BusinessError } from './types/BusinessError.js';
|
|
10
|
-
export { createSuccessResult, createErrorResult } from './types/ServiceResult.js';
|
|
9
|
+
export { createSuccessResult, createErrorResult, handleRepositoryError } from './types/ServiceResult.js';
|
|
11
10
|
// ============================================================================
|
|
12
11
|
// VALIDATION
|
|
13
12
|
// ============================================================================
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,eAAe;AACf,+EAA+E;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAEzG,+EAA+E;AAC/E,aAAa;AACb,+EAA+E;AAE/E,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC"}
|
|
@@ -28,4 +28,15 @@ export declare function createSuccessResult<T>(data: T, metadata?: any): Service
|
|
|
28
28
|
* Helper to create error result
|
|
29
29
|
*/
|
|
30
30
|
export declare function createErrorResult(error: BusinessError | Error | any): ServiceResult;
|
|
31
|
+
/**
|
|
32
|
+
* Transform repository errors into business errors
|
|
33
|
+
* @param error - Original error from repository layer (anything may be thrown)
|
|
34
|
+
* @returns The error itself when it is already a BusinessError, otherwise a
|
|
35
|
+
* BusinessError with appropriate context
|
|
36
|
+
*
|
|
37
|
+
* Driver codes are checked first, through the whole cause chain: a QueryError
|
|
38
|
+
* from db-core always carries code 'QUERY_ERROR', with the driver error (and its
|
|
39
|
+
* real code) in `cause`. "Not found" is never derived from message text.
|
|
40
|
+
*/
|
|
41
|
+
export declare function handleRepositoryError(error: unknown): BusinessError;
|
|
31
42
|
//# sourceMappingURL=ServiceResult.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServiceResult.d.ts","sourceRoot":"","sources":["../../src/types/ServiceResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,GAAG,GAAG;IAClC,kCAAkC;IAClC,OAAO,EAAE,OAAO,CAAC;IAEjB,kCAAkC;IAClC,IAAI,CAAC,EAAE,CAAC,CAAC;IAET,oCAAoC;IACpC,KAAK,CAAC,EAAE;QACJ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KACjC,CAAC;IAEF,yBAAyB;IACzB,QAAQ,CAAC,EAAE;QACP,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;CACL;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,aAAa,CAAC,CAAC,CAAC,CAShF;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,aAAa,GAAG,KAAK,GAAG,GAAG,GAAG,aAAa,
|
|
1
|
+
{"version":3,"file":"ServiceResult.d.ts","sourceRoot":"","sources":["../../src/types/ServiceResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,GAAG,GAAG;IAClC,kCAAkC;IAClC,OAAO,EAAE,OAAO,CAAC;IAEjB,kCAAkC;IAClC,IAAI,CAAC,EAAE,CAAC,CAAC;IAET,oCAAoC;IACpC,KAAK,CAAC,EAAE;QACJ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;KACjC,CAAC;IAEF,yBAAyB;IACzB,QAAQ,CAAC,EAAE;QACP,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;CACL;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,aAAa,CAAC,CAAC,CAAC,CAShF;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,aAAa,GAAG,KAAK,GAAG,GAAG,GAAG,aAAa,CAcnF;AAqGD;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,CAmBnE"}
|
|
@@ -16,9 +16,7 @@ export function createSuccessResult(data, metadata) {
|
|
|
16
16
|
* Helper to create error result
|
|
17
17
|
*/
|
|
18
18
|
export function createErrorResult(error) {
|
|
19
|
-
|
|
20
|
-
error = handleRepositoryError(error);
|
|
21
|
-
}
|
|
19
|
+
error = handleRepositoryError(error);
|
|
22
20
|
return {
|
|
23
21
|
success: false,
|
|
24
22
|
error: {
|
|
@@ -31,30 +29,113 @@ export function createErrorResult(error) {
|
|
|
31
29
|
}
|
|
32
30
|
};
|
|
33
31
|
}
|
|
32
|
+
const MESSAGES = {
|
|
33
|
+
DUPLICATE_RESOURCE: 'Recurso já existe',
|
|
34
|
+
CONSTRAINT_VIOLATION: 'Referência inválida ou violação de restrição',
|
|
35
|
+
RESOURCE_IN_USE: 'Recurso em uso por outros registos',
|
|
36
|
+
INVALID_VALUE: 'Valor inválido ou demasiado longo para a base de dados',
|
|
37
|
+
DATABASE_TIMEOUT: 'Operação no banco de dados expirou ou ficou bloqueada'
|
|
38
|
+
};
|
|
39
|
+
/** MySQL/MariaDB error codes (mysql2 `error.code`). */
|
|
40
|
+
const MYSQL_CODES = {
|
|
41
|
+
ER_DUP_ENTRY: 'DUPLICATE_RESOURCE',
|
|
42
|
+
ER_DUP_ENTRY_WITH_KEY_NAME: 'DUPLICATE_RESOURCE',
|
|
43
|
+
ER_NO_REFERENCED_ROW: 'CONSTRAINT_VIOLATION',
|
|
44
|
+
ER_NO_REFERENCED_ROW_2: 'CONSTRAINT_VIOLATION',
|
|
45
|
+
ER_CHECK_CONSTRAINT_VIOLATED: 'CONSTRAINT_VIOLATION',
|
|
46
|
+
ER_ROW_IS_REFERENCED: 'RESOURCE_IN_USE',
|
|
47
|
+
ER_ROW_IS_REFERENCED_2: 'RESOURCE_IN_USE',
|
|
48
|
+
ER_DATA_TOO_LONG: 'INVALID_VALUE',
|
|
49
|
+
ER_TRUNCATED_WRONG_VALUE: 'INVALID_VALUE',
|
|
50
|
+
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: 'INVALID_VALUE',
|
|
51
|
+
ER_WARN_DATA_OUT_OF_RANGE: 'INVALID_VALUE',
|
|
52
|
+
ER_BAD_NULL_ERROR: 'INVALID_VALUE',
|
|
53
|
+
ER_LOCK_DEADLOCK: 'DATABASE_TIMEOUT',
|
|
54
|
+
ER_LOCK_WAIT_TIMEOUT: 'DATABASE_TIMEOUT'
|
|
55
|
+
};
|
|
56
|
+
/** PostgreSQL SQLSTATE codes (pg `error.code`). */
|
|
57
|
+
const POSTGRES_CODES = {
|
|
58
|
+
'23505': 'DUPLICATE_RESOURCE', // unique_violation
|
|
59
|
+
'23503': 'CONSTRAINT_VIOLATION', // foreign_key_violation (see below for deletes)
|
|
60
|
+
'23514': 'CONSTRAINT_VIOLATION', // check_violation
|
|
61
|
+
'23P01': 'CONSTRAINT_VIOLATION', // exclusion_violation
|
|
62
|
+
'23502': 'INVALID_VALUE', // not_null_violation
|
|
63
|
+
'22001': 'INVALID_VALUE', // string_data_right_truncation
|
|
64
|
+
'22003': 'INVALID_VALUE', // numeric_value_out_of_range
|
|
65
|
+
'22007': 'INVALID_VALUE', // invalid_datetime_format
|
|
66
|
+
'22008': 'INVALID_VALUE', // datetime_field_overflow
|
|
67
|
+
'22P02': 'INVALID_VALUE', // invalid_text_representation
|
|
68
|
+
'40P01': 'DATABASE_TIMEOUT', // deadlock_detected
|
|
69
|
+
'55P03': 'DATABASE_TIMEOUT', // lock_not_available
|
|
70
|
+
'57014': 'DATABASE_TIMEOUT' // query_canceled (statement_timeout)
|
|
71
|
+
};
|
|
72
|
+
/** The error and its causes (QueryError -> driver error), outermost first. */
|
|
73
|
+
function errorChain(error) {
|
|
74
|
+
const chain = [];
|
|
75
|
+
let current = error;
|
|
76
|
+
while (current && typeof current === 'object' && chain.length < 10 && !chain.includes(current)) {
|
|
77
|
+
chain.push(current);
|
|
78
|
+
current = current.cause ?? current.originalError;
|
|
79
|
+
}
|
|
80
|
+
return chain;
|
|
81
|
+
}
|
|
82
|
+
/** Classification by the driver's error code. */
|
|
83
|
+
function kindFromDriverCode(chain) {
|
|
84
|
+
for (const link of chain) {
|
|
85
|
+
if (typeof link.code !== 'string')
|
|
86
|
+
continue;
|
|
87
|
+
const mysql = MYSQL_CODES[link.code];
|
|
88
|
+
if (mysql)
|
|
89
|
+
return mysql;
|
|
90
|
+
const postgres = POSTGRES_CODES[link.code];
|
|
91
|
+
if (postgres === 'CONSTRAINT_VIOLATION' && link.code === '23503') {
|
|
92
|
+
// Same SQLSTATE for "referenced row missing" (insert/update) and
|
|
93
|
+
// "row still referenced" (delete); told apart by the detail.
|
|
94
|
+
return typeof link.detail === 'string' && /still referenced/i.test(link.detail)
|
|
95
|
+
? 'RESOURCE_IN_USE'
|
|
96
|
+
: 'CONSTRAINT_VIOLATION';
|
|
97
|
+
}
|
|
98
|
+
if (postgres)
|
|
99
|
+
return postgres;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
/** Classification by message, for errors without a known driver code. */
|
|
104
|
+
function kindFromMessage(message) {
|
|
105
|
+
const text = message.toLowerCase();
|
|
106
|
+
if (text.includes('duplicate') || text.includes('unique constraint'))
|
|
107
|
+
return 'DUPLICATE_RESOURCE';
|
|
108
|
+
if (text.includes('foreign key'))
|
|
109
|
+
return 'CONSTRAINT_VIOLATION';
|
|
110
|
+
if (text.includes('deadlock') || text.includes('lock wait timeout') || text.includes('etimedout')) {
|
|
111
|
+
return 'DATABASE_TIMEOUT';
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
34
115
|
/**
|
|
35
116
|
* Transform repository errors into business errors
|
|
36
|
-
* @param error - Original error from repository layer
|
|
37
|
-
* @returns BusinessError
|
|
117
|
+
* @param error - Original error from repository layer (anything may be thrown)
|
|
118
|
+
* @returns The error itself when it is already a BusinessError, otherwise a
|
|
119
|
+
* BusinessError with appropriate context
|
|
120
|
+
*
|
|
121
|
+
* Driver codes are checked first, through the whole cause chain: a QueryError
|
|
122
|
+
* from db-core always carries code 'QUERY_ERROR', with the driver error (and its
|
|
123
|
+
* real code) in `cause`. "Not found" is never derived from message text.
|
|
38
124
|
*/
|
|
39
|
-
function handleRepositoryError(error) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
return new BusinessError('Execução inválida na base de dados.', 'QUERY_ERROR', error);
|
|
43
|
-
}
|
|
44
|
-
// Handle common database constraint violations
|
|
45
|
-
if (error.message.includes('duplicate') || error.message.includes('unique')) {
|
|
46
|
-
return new BusinessError('Recurso já existe', 'DUPLICATE_RESOURCE', error);
|
|
47
|
-
}
|
|
48
|
-
if (error.message.includes('not found') || error.message.includes('does not exist')) {
|
|
49
|
-
return new BusinessError('Recurso não encontrado', 'RESOURCE_NOT_FOUND', error);
|
|
125
|
+
export function handleRepositoryError(error) {
|
|
126
|
+
if (BusinessError.isBusinessError(error)) {
|
|
127
|
+
return error;
|
|
50
128
|
}
|
|
51
|
-
|
|
52
|
-
|
|
129
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
130
|
+
const chain = errorChain(error);
|
|
131
|
+
const kind = kindFromDriverCode(chain) ?? kindFromMessage(cause.message);
|
|
132
|
+
if (kind) {
|
|
133
|
+
return new BusinessError(MESSAGES[kind], kind, cause);
|
|
53
134
|
}
|
|
54
|
-
if (
|
|
55
|
-
return new BusinessError('
|
|
135
|
+
if (chain.some(link => link.code === 'QUERY_ERROR')) {
|
|
136
|
+
return new BusinessError('Execução inválida na base de dados.', 'QUERY_ERROR', cause);
|
|
56
137
|
}
|
|
57
138
|
// Default: wrap as generic business error
|
|
58
|
-
return new BusinessError('Operação falhou', 'OPERATION_FAILED',
|
|
139
|
+
return new BusinessError('Operação falhou', 'OPERATION_FAILED', cause);
|
|
59
140
|
}
|
|
60
141
|
//# sourceMappingURL=ServiceResult.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServiceResult.js","sourceRoot":"","sources":["../../src/types/ServiceResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AA2BnD;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAI,IAAO,EAAE,QAAc;IAC1D,OAAO;QACH,OAAO,EAAE,IAAI;QACb,IAAI;QACJ,QAAQ,EAAE;YACN,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,GAAG,QAAQ;SACd;KACJ,CAAC;AACN,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAkC;IAChE,
|
|
1
|
+
{"version":3,"file":"ServiceResult.js","sourceRoot":"","sources":["../../src/types/ServiceResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AA2BnD;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAI,IAAO,EAAE,QAAc;IAC1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AC;IACxE,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IAEhC,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,CAAC,IAAI,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACzE,IAAI,IAAI,EAAE,CAAC;QACP,OAAO,IAAI,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC,EAAE,CAAC;QAClD,OAAO,IAAI,aAAa,CAAC,qCAAqC,EAAE,aAAa,EAAE,KAAK,CAAC,CAAC;IAC1F,CAAC;IAED,0CAA0C;IAC1C,OAAO,IAAI,aAAa,CAAC,iBAAiB,EAAE,kBAAkB,EAAE,KAAK,CAAC,CAAC;AAC3E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@groundbrick/service-base",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Service layer base classes with validation, error handling, business logic patterns, and generic email infrastructure",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -17,12 +17,6 @@
|
|
|
17
17
|
"README.md",
|
|
18
18
|
"LICENSE"
|
|
19
19
|
],
|
|
20
|
-
"scripts": {
|
|
21
|
-
"build": "tsc --build",
|
|
22
|
-
"clean": "rm -rf dist *.tsbuildinfo",
|
|
23
|
-
"lint": "eslint src/**/*.ts",
|
|
24
|
-
"lint:fix": "eslint src/**/*.ts --fix"
|
|
25
|
-
},
|
|
26
20
|
"keywords": [
|
|
27
21
|
"typescript",
|
|
28
22
|
"service-layer",
|
|
@@ -38,21 +32,29 @@
|
|
|
38
32
|
"license": "MIT",
|
|
39
33
|
"repository": {
|
|
40
34
|
"type": "git",
|
|
41
|
-
"url": "git+https://github.com/200Systems/
|
|
35
|
+
"url": "git+https://github.com/200Systems/groundbrick.git",
|
|
42
36
|
"directory": "packages/service-base"
|
|
43
37
|
},
|
|
44
38
|
"dependencies": {
|
|
45
|
-
"@groundbrick/db-core": "^0.
|
|
46
|
-
"@groundbrick/logger": "^0.
|
|
39
|
+
"@groundbrick/db-core": "^0.4.0",
|
|
40
|
+
"@groundbrick/logger": "^0.5.1"
|
|
47
41
|
},
|
|
48
42
|
"devDependencies": {
|
|
49
43
|
"@types/node": "^20.10.0",
|
|
50
|
-
"typescript": "^5.8.3"
|
|
44
|
+
"typescript": "^5.8.3",
|
|
45
|
+
"vitest": "^2.0.0"
|
|
51
46
|
},
|
|
52
47
|
"engines": {
|
|
53
48
|
"node": ">=18.0.0"
|
|
54
49
|
},
|
|
55
50
|
"publishConfig": {
|
|
56
51
|
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsc --build",
|
|
55
|
+
"clean": "rm -rf dist *.tsbuildinfo",
|
|
56
|
+
"lint": "eslint src/**/*.ts",
|
|
57
|
+
"lint:fix": "eslint src/**/*.ts --fix",
|
|
58
|
+
"test": "vitest run"
|
|
57
59
|
}
|
|
58
|
-
}
|
|
60
|
+
}
|