---
name: service-layer
description: This skill should be used when the user asks about "service layer pattern", "when to use service layer", "business logic layer", "application service", "transaction script", or mentions needing to organize business logic and define application boundaries.
version: 1.0.0
---

# Service Layer Pattern

## What Is It
The Service Layer pattern defines an application's boundary with a layer of services that establish the set of available operations and coordinate the application's response in each operation. It encapsulates business logic and orchestrates domain objects.

## When to Use
- **Complex business logic** - Coordinate multiple domain objects
- **Transaction management** - Group operations in transactions
- **API design** - Define clear application boundaries
- **Layered architecture** - Separate presentation from business logic
- **Multiple clients** - Share business logic across controllers

## When NOT to Use
- **Simple CRUD** - Direct repository access is simpler
- **Thin wrappers** - No value if just delegating
- **Performance critical** - Adds indirection overhead
- **Small applications** - May be overkill

## How to Implement

### Implementation Steps
1. Define service interfaces for each domain area
2. Implement services with business logic
3. Inject dependencies (repositories, other services)
4. Handle transactions at service boundary
5. Controllers call services, not repositories directly

### TypeScript Implementation

```typescript
class OrderService {
  constructor(
    private orderRepo: OrderRepository,
    private productRepo: ProductRepository,
    private emailService: EmailService
  ) {}

  async placeOrder(customerId: string, items: OrderItem[]): Promise<Order> {
    // Validate products exist
    for (const item of items) {
      const product = await this.productRepo.findById(item.productId);
      if (!product) throw new Error('Product not found');
    }

    // Create order
    const order = new Order(customerId, items);
    await this.orderRepo.save(order);

    // Send confirmation
    await this.emailService.sendConfirmation(customerId, order);

    return order;
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/service-layer.ts` - Basic implementation with transaction management
- `examples/service-layer-advanced.ts` - Real-world example with multiple services

## Related Patterns
- **Repository** - Services use repositories for data access
- **Unit of Work** - Services manage transactions
- **Facade** - Service layer acts as facade to domain
