The Infrastructure Layer handles technical details required by the application, such as persistence, messaging, and external integrations. This layer implements the interfaces defined in the domain or application layers.
Common implementations include:
- Repositories: Concrete implementations for database access (e.g.,
InMemoryCustomerRepository, SqlOrderRepository). - Event Publishers: Implementations for broadcasting domain events (e.g.,
SimpleDomainEventPublisher). - External Clients: API clients for third-party services.
// Example: In-memory Repository implementation
class InMemoryCustomerRepository implements CustomerRepository {
private customers: Map<string, Customer> = new Map();
async findById(id: CustomerId): Promise<Customer | null> {
const customer = this.customers.get(id.toString());
return customer || null;
}
async save(customer: Customer): Promise<void> {
this.customers.set(customer.customerId.toString(), customer);
}
}
// Example: Simple Domain Event Publisher
class SimpleDomainEventPublisher implements DomainEventPublisher {
private handlers: Map<string, Array<(event: DomainEvent) => void>> = new Map();
publish<T extends DomainEvent>(event: T): void {
const eventType = event.constructor.name;
const eventHandlers = this.handlers.get(eventType) || [];
for (const handler of eventHandlers) {
try {
handler(event);
} catch (error) {
console.error(`Error handling event ${eventType}:`, error);
}
}
}
subscribe<T extends DomainEvent>(
eventType: new (...args: any[]) => T,
handler: (event: T) => void,
): void {
const eventName = eventType.name;
if (!this.handlers.has(eventName)) {
this.handlers.set(eventName, []);
}
this.handlers.get(eventName)!.push(handler as any);
}
}