Overview
Create objects without specifying their concrete classes
Factory Pattern
6 implementations available
When to Use
- When you need to abstract data access logic
- When you want to make your code testable
- When you need to support multiple data sources
- When you want to decouple business logic from infrastructure
Available Implementations
Response Helpers
Standardized API response builders with type-safe schemas
npx hanma add elysia-response --framework elysia
Success/error buildersTypeBox schemasPaginated responses
HTML Plugin
HTML response helpers for server-side rendering
npx hanma add elysia-html --framework elysia
HTML responsesTemplate helpersElement builders
Pagination
Cursor and offset pagination with TypeBox schemas
npx hanma add elysia-pagination --framework elysia
Offset paginationCursor paginationTypeBox schemas
Crypto Utilities
Cryptographic utilities using Bun's native APIs
npx hanma add elysia-crypto --framework elysia
Bun password hashingToken generationHMAC signatures
TypeBox Patterns
Advanced TypeBox validation patterns with custom validators
npx hanma add elysia-typebox --framework elysia
Custom validatorsReusable schemasSchema composition
CRUD Route Factory
Generic CRUD route factory with service pattern and hooks
npx hanma add elysia-crud --framework elysia
Full CRUD operationsPagination built-inService pattern
Basic Example
// Factory Pattern implementation example
// This shows the basic structure of factory pattern in Elysia
// Define your interface
interface IRepository {
findAll(): Promise<T[]>;
findById(id: string): Promise<T | null>;
create(data: CreateDto): Promise<T>;
update(id: string, data: UpdateDto): Promise<T>;
delete(id: string): Promise<void>;
}
// Implement the pattern
class FactoryRepository implements IRepository {
async findAll(): Promise<T[]> {
// Implementation
}
async findById(id: string): Promise<T | null> {
// Implementation
}
async create(data: CreateDto): Promise<T> {
// Implementation
}
async update(id: string, data: UpdateDto): Promise<T> {
// Implementation
}
async delete(id: string): Promise<void> {
// Implementation
}
}
// Use the pattern
const repository = new FactoryRepository();
const items = await repository.findAll();
Frequently Asked Questions
What is Factory Pattern?
Create objects without specifying their concrete classes. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Factory Pattern work with Elysia?
Elysia provides excellent support for this pattern through its dependency injection system and middleware composition.
What are the benefits?
Improved testability, separation of concerns, easier maintenance, and flexibility to change implementations without affecting business logic.
When should I avoid this pattern?
For very simple applications with minimal logic, the pattern may add unnecessary complexity. Use judgment based on project requirements.