@groundbrick/service-base 0.3.0 → 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 CHANGED
@@ -1,36 +1,6 @@
1
1
  # @groundbrick/service-base
2
2
 
3
- 🧠 Service layer foundation with validation, logging, error handling, and transaction support.
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
- ## Dependencies
11
+ Depends on `@groundbrick/logger` (logging) and `@groundbrick/db-core` (database interfaces).
12
+
13
+ ## Exports
42
14
 
43
- This package requires:
44
- - `@groundbrick/logger` - Logging functionality
45
- - `@groundbrick/db-core` - Database interfaces
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
- // 2. Business logic
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
- if (BusinessError.isBusinessError(error)) {
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?: ServiceOptions
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
- // 4. Create order items using the order ID
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
- #### 🔧 Repository Method Requirements:
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
- export class ProductService extends BaseService {
303
- constructor(private productRepository: ProductRepository) {
304
- super();
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
- // Create product logic...
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 Methods
148
+ #### Protected Members
348
149
 
349
150
  ```typescript
350
- // Validation
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
- ### 🛡 BusinessError
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
- Custom error class for business logic errors.
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
- ### ValidationHelper
192
+ `toJSON` includes the stack and the context; `toUserResponse` does not.
393
193
 
394
- Pre-built validation rules for common scenarios.
194
+ ### ServiceResult
395
195
 
396
196
  ```typescript
397
- class ValidationHelper {
398
- // Basic rules
399
- static required(): ValidationRule
400
- static minLength(min: number): ValidationRule
401
- static maxLength(max: number): ValidationRule
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
- The `handleRepositoryError` method automatically transforms common database errors:
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
- ### 2. Structured Error Responses
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
- if (BusinessError.isBusinessError(error)) {
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
- ## Transaction Management
527
-
528
- ### Simple Transaction
219
+ ### Validator
529
220
 
530
221
  ```typescript
531
- async updateUserProfile(userId: number, profileData: any): Promise<User> {
532
- return await this.withTransaction(async (tx) => {
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
- // Update user preferences
540
- await this.preferencesRepository.updateWithTransaction(tx, userId, {
541
- theme: profileData.theme,
542
- language: profileData.language
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
- ### Complex Business Transaction
551
-
552
- ```typescript
553
- async processOrder(orderData: CreateOrderRequest): Promise<Order> {
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
- ## Best Practices
238
+ All the rules of a field run, in order. Rules are synchronous and return an error message or `null`.
583
239
 
584
- ### 1. Keep Services Focused
240
+ ### ValidationHelper
585
241
 
586
242
  ```typescript
587
- // ✅ Good - Single responsibility
588
- class UserService extends BaseService {
589
- async createUser(userData: CreateUserRequest): Promise<User> { }
590
- async updateUser(id: number, updates: UpdateUserRequest): Promise<User> { }
591
- async getUserById(id: number): Promise<User> { }
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
- // ❌ Bad - Too many responsibilities
595
- class UserService extends BaseService {
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
- ### 2. Validate Input Early
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
- ```typescript
605
- // ✅ Good - Validate first
606
- async createUser(userData: CreateUserRequest): Promise<User> {
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
- // ❌ Bad - Validation mixed with business logic
618
- async createUser(userData: CreateUserRequest): Promise<User> {
619
- const existingUser = await this.userRepository.findByEmail(userData.email);
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
- ### 3. Use Transactions for Multi-Repository Operations
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
- // ✅ Good - Transaction for consistency
631
- async transferFunds(fromAccount: number, toAccount: number, amount: number): Promise<void> {
632
- await this.withTransaction(async (tx) => {
633
- await this.accountRepository.decrementBalanceWithTransaction(tx, fromAccount, amount);
634
- await this.accountRepository.incrementBalanceWithTransaction(tx, toAccount, amount);
635
- await this.transactionRepository.createWithTransaction(tx, {
636
- from_account: fromAccount,
637
- to_account: toAccount,
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
- ```typescript
654
- // ✅ Good - Structured error handling
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
- ## Integration with Other Packages
676
-
677
- This service layer integrates seamlessly with other microframework packages:
287
+ ## Repository Errors
678
288
 
679
- ```typescript
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
- // Initialize repository
694
- const userRepository = new UserRepository(db);
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
- // Initialize service with database for transaction support
697
- const userService = new UserService(userRepository, { database: db });
301
+ The messages are in Portuguese and the original error is in `originalError`.
698
302
 
699
- // Use in application
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
-
@@ -1 +1 @@
1
- {"version":3,"file":"Ba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,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"}
@@ -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() // Database client knows its type
63
+ dbType: this.db.getDatabaseType()
64
64
  });
65
65
  try {
66
- // Use the database client's transaction method which handles commit/rollback automatically
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() // Transaction knows its type too!
70
+ dbType: transaction.getDatabaseType()
71
71
  });
72
72
  return await callback(transaction);
73
73
  });
@@ -76,15 +76,13 @@ export class BaseService {
76
76
  }
77
77
  catch (error) {
78
78
  if (BusinessError.isBusinessError(error)) {
79
- // A business rule aborted the unit of work (e.g. NOT_FOUND): expected, not an error.
79
+ // A business rule aborted the unit of work (e.g. NOT_FOUND)
80
80
  this.logger.debug('Transaction aborted', { transactionId, code: error.code });
81
81
  }
82
82
  else {
83
83
  this.logger.error('Transaction failed', error instanceof Error ? error : new Error(String(error)), { transactionId });
84
84
  }
85
- // Rethrow the error untouched so its class, name and code reach the
86
- // HTTP layer (NotFoundError stays a 404). Only a non-Error throw is
87
- // mapped, so callers can always rely on an Error.
85
+ // Rethrows an Error untouched; a non-Error throw is mapped to a BusinessError.
88
86
  throw error instanceof Error ? error : this.handleRepositoryError(error);
89
87
  }
90
88
  }
@@ -1 +1 @@
1
- {"version":3,"file":"BaseService.js","sourceRoot":"","sources":["../../src/core/BaseService.ts"],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AAS,CAAC,GAAG,CAAC,CAAC,CAAC;QAC3C,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,EAAE,KAAK,EAAE,4BAA4B,EAAE,CAAC;QACnD,CAAC;IACL,CAAC;CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,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"}
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
  // ============================================================================
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAqC;AAErC,+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"}
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"}
@@ -36,8 +36,7 @@ export declare function createErrorResult(error: BusinessError | Error | any): S
36
36
  *
37
37
  * Driver codes are checked first, through the whole cause chain: a QueryError
38
38
  * from db-core always carries code 'QUERY_ERROR', with the driver error (and its
39
- * real code) in `cause`. Deliberately no "not found" mapping from message text:
40
- * "column x does not exist" is a schema bug (500), not a missing resource (404).
39
+ * real code) in `cause`. "Not found" is never derived from message text.
41
40
  */
42
41
  export declare function handleRepositoryError(error: unknown): BusinessError;
43
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,CAcnF;AAqGD;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,CAmBnE"}
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"}
@@ -79,7 +79,7 @@ function errorChain(error) {
79
79
  }
80
80
  return chain;
81
81
  }
82
- /** Classification by the driver's error code, which is exact and language independent. */
82
+ /** Classification by the driver's error code. */
83
83
  function kindFromDriverCode(chain) {
84
84
  for (const link of chain) {
85
85
  if (typeof link.code !== 'string')
@@ -90,7 +90,7 @@ function kindFromDriverCode(chain) {
90
90
  const postgres = POSTGRES_CODES[link.code];
91
91
  if (postgres === 'CONSTRAINT_VIOLATION' && link.code === '23503') {
92
92
  // Same SQLSTATE for "referenced row missing" (insert/update) and
93
- // "row still referenced" (delete); only the detail tells them apart.
93
+ // "row still referenced" (delete); told apart by the detail.
94
94
  return typeof link.detail === 'string' && /still referenced/i.test(link.detail)
95
95
  ? 'RESOURCE_IN_USE'
96
96
  : 'CONSTRAINT_VIOLATION';
@@ -100,7 +100,7 @@ function kindFromDriverCode(chain) {
100
100
  }
101
101
  return undefined;
102
102
  }
103
- /** Last resort for errors without a driver code (other drivers, wrapped errors). */
103
+ /** Classification by message, for errors without a known driver code. */
104
104
  function kindFromMessage(message) {
105
105
  const text = message.toLowerCase();
106
106
  if (text.includes('duplicate') || text.includes('unique constraint'))
@@ -120,8 +120,7 @@ function kindFromMessage(message) {
120
120
  *
121
121
  * Driver codes are checked first, through the whole cause chain: a QueryError
122
122
  * from db-core always carries code 'QUERY_ERROR', with the driver error (and its
123
- * real code) in `cause`. Deliberately no "not found" mapping from message text:
124
- * "column x does not exist" is a schema bug (500), not a missing resource (404).
123
+ * real code) in `cause`. "Not found" is never derived from message text.
125
124
  */
126
125
  export function handleRepositoryError(error) {
127
126
  if (BusinessError.isBusinessError(error)) {
@@ -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,KAAK,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;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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",
@@ -32,12 +32,12 @@
32
32
  "license": "MIT",
33
33
  "repository": {
34
34
  "type": "git",
35
- "url": "git+https://github.com/200Systems/bitbrick-microframework.git",
35
+ "url": "git+https://github.com/200Systems/groundbrick.git",
36
36
  "directory": "packages/service-base"
37
37
  },
38
38
  "dependencies": {
39
- "@groundbrick/db-core": "^0.3.0",
40
- "@groundbrick/logger": "^0.4.3"
39
+ "@groundbrick/db-core": "^0.4.0",
40
+ "@groundbrick/logger": "^0.5.1"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^20.10.0",