What is the Repository Pattern?
The repository pattern creates an abstraction layer between your application logic and data storage. Instead of scattering Firestore queries throughout your code, you centralize all database operations in repository classes. This provides several key benefits:- Separation of concerns: Business logic stays separate from data access code
- Testability: Easy to mock repositories for unit testing
- Consistency: Standardized way to interact with your data
- Type safety: Full TypeScript support with compile-time checks
Why Use Repositories?
Firebase’s native SDK is powerful but verbose. Simple operations require multiple lines of boilerplate code, and there’s no built-in validation or type safety. The repository pattern solves this by providing:- Cleaner code: One-line operations instead of callback chains
- Automatic validation: Integrate Zod schemas for runtime type checking
- Built-in features: Soft deletes, lifecycle hooks, and error handling
- Consistent API: Same methods across all collections
Creating a Repository
Basic Repository
The simplest way to create a repository is to instantiateFirestoreRepository with your Firestore instance and collection name:
Repository with Schema Validation
For production applications, you’ll want validation. Use thewithSchema static method to create a repository with Zod schema validation:
Core Operations
Create Documents
Read Documents
Update Documents
Delete Documents
Advanced Querying
The repository provides a fluent query builder for complex queries:Subcollections
FirestoreORM makes working with subcollections intuitive:Transactions
FirestoreORM provides a clean API for Firestore transactions:Real-time Updates
Subscribe to real-time changes using the query builder:Error Handling
FirestoreORM provides custom error types for better error handling:Best Practices
1. Create Repository Modules
Organize repositories in dedicated modules:2. Use Type-Safe Schemas
Define your schemas alongside your types:3. Leverage Bulk Operations
Use bulk methods for better performance:4. Use Soft Deletes by Default
Soft deletes allow data recovery and audit trails:What’s Next?
- Learn about Schema Validation for runtime type safety
- Explore Soft Deletes for recoverable deletion
- Discover Lifecycle Hooks for side effects and logging