Why Schema Validation?
TypeScript provides compile-time type safety, but runtime data can come from anywhere - user input, external APIs, or legacy data. Schema validation ensures your data is valid before it reaches Firestore, preventing:- Invalid data in your database: Catch errors before they’re persisted
- Runtime errors: Prevent crashes from unexpected data shapes
- Data inconsistency: Enforce business rules at the data layer
- Silent failures: Get clear error messages about what went wrong
How It Works
FirestoreORM uses Zod for schema validation. When you create a repository with a schema, all create and update operations automatically validate data against your schema:Implementation Details
Let’s look at how FirestoreORM implements validation internally:The Validator Interface
Fromsrc/core/Validation.ts:4-7:
parseCreate: Validates complete documents (all required fields)parseUpdate: Validates partial updates (all fields optional)
Making a Validator
Fromsrc/core/Validation.ts:9-18:
makeValidator function:
- Takes a Zod schema for creation
- Optionally takes a separate schema for updates
- If no update schema provided, uses
createSchema.partial()to make all fields optional - Returns a validator that parses data appropriately
Validation During Create
Fromsrc/core/FirestoreRepository.ts:307-325:
ZodError, which gets caught and converted to FirestoreORM’s ValidationError on line 321.
Validation During Update
Fromsrc/core/FirestoreRepository.ts:443-478:
parseUpdate on line 456, which validates partial data. This allows updating individual fields without providing the entire document.
Defining Schemas
Basic Schema
Schema with Optional Fields
Nested Object Schemas
Array Schemas
Custom Validations
Refinements and Transformations
Handling Validation Errors
ValidationError Structure
Fromsrc/core/Errors.ts:39-46:
ValidationError class contains:
issues: Array of Zod validation issues with detailed informationmessage: Formatted error message showing all failures
Basic Error Handling
Building User-Friendly Error Messages
API Response Example
Separate Create and Update Schemas
Sometimes you need different validation rules for creating vs updating:Validation in Bulk Operations
All bulk operations validate each item:Validation in Transactions
Validation works seamlessly in transactions:Performance Considerations
Validation is Fast
Zod’s validation is highly optimized and adds minimal overhead:When to Skip Validation
There are rare cases where you might want to skip validation:Best Practices
1. Define Schemas Alongside Types
2. Use Descriptive Error Messages
3. Share Schemas Between Frontend and Backend
4. Validate Business Rules
What’s Next?
- Explore Soft Deletes for recoverable deletion
- Learn about Lifecycle Hooks for validation side effects
- Check the Repository Pattern guide