What are Lifecycle Hooks?
Lifecycle hooks let you run custom code at specific points in a repository operation’s lifecycle. You can add logging, send notifications, validate business rules, update related data, or trigger any side effect before or after database operations. Think of hooks as middleware for your database operations - they intercept the flow of execution and let you inject custom behavior without modifying the core operation logic.Why Use Hooks?
Hooks provide a clean separation between:- Core data operations: Creating, reading, updating, deleting
- Side effects: Logging, notifications, analytics, cache invalidation
- Centralized logic: Define side effects once, apply automatically to all operations
- Maintainability: Easy to add/remove behaviors without touching business logic
- Testability: Mock or disable hooks during testing
- Consistency: Ensure certain actions always happen (e.g., audit logging)
Available Hooks
Single Document Hooks
Fromsrc/core/FirestoreRepository.ts:16-21:
beforeCreate/afterCreate: Creating a single documentbeforeUpdate/afterUpdate: Updating a single documentbeforeDelete/afterDelete: Hard deleting a documentbeforeSoftDelete/afterSoftDelete: Soft deleting a documentbeforeRestore/afterRestore: Restoring a soft-deleted document
Bulk Operation Hooks
Fromsrc/core/FirestoreRepository.ts:23-28:
beforeBulkCreate/afterBulkCreate: Creating multiple documentsbeforeBulkUpdate/afterBulkUpdate: Updating multiple documentsbeforeBulkDelete/afterBulkDelete: Hard deleting multiple documentsbeforeBulkSoftDelete/afterBulkSoftDelete: Soft deleting multiple documentsbeforeBulkRestore/afterBulkRestore: Restoring multiple documents
How Hooks Work Internally
Hook Registration
Fromsrc/core/FirestoreRepository.ts:261-270:
Hook Execution
Fromsrc/core/FirestoreRepository.ts:272-275:
Hook Integration in Operations
Let’s see how hooks integrate into a create operation, fromsrc/core/FirestoreRepository.ts:307-325:
- Validate data (line 309)
- Run
beforeCreatehooks (line 312) - Write to Firestore (line 314)
- Run
afterCreatehooks (line 317) - Return result
Basic Hook Usage
Simple Logging
Async Operations
Hooks can be async functions:Validation Hooks
Advanced Hook Patterns
Audit Logging
Cache Invalidation
Notification System
Analytics Tracking
Bulk Operation Hooks
Bulk Create Hook
Fromsrc/core/FirestoreRepository.ts:352-375:
Bulk Delete Hook
Fromsrc/core/FirestoreRepository.ts:659-696:
Real-World Examples
E-commerce Order Processing
User Management System
Content Publishing Platform
Error Handling in Hooks
Hook Errors Fail the Operation
Graceful Error Handling
Best Practices
1. Keep Hooks Focused
2. Use Before Hooks for Validation
3. Use After Hooks for Side Effects
4. Handle Errors Appropriately
5. Avoid Infinite Loops
What’s Next?
- Learn about Repository Pattern for overall structure
- Explore Schema Validation to combine with hooks
- Review Soft Deletes for deletion lifecycle hooks