# Service Layer Patterns {#service-layer-patterns}


Architecture and patterns for the Gauzy service layer.


## Base Service {#base-service}


All services extend `TenantAwareCrudService`, which provides:

- Automatic tenant scoping
- Standard CRUD operations
- Pagination support

```typescript
@Injectable()
export class EmployeeService extends TenantAwareCrudService<Employee> {
  constructor(
    @InjectRepository(Employee)
    private readonly employeeRepo: Repository<Employee>,
  ) {
    super(employeeRepo);
  }

  // Custom methods
  async findActiveByOrg(orgId: string): Promise<Employee[]> {
    return this.repository.find({
      where: {
        organizationId: orgId,
        isActive: true,
        tenantId: RequestContext.currentTenantId(),
      },
    });
  }
}
```


## Service Hierarchy {#service-hierarchy}






```mermaid
graph TB
    CrudService[CrudService - Base CRUD]
    TenantBase[TenantAwareCrudService - Tenant Scoping]
    Concrete[EmployeeService - Business Logic]

    CrudService --> TenantBase
    TenantBase --> Concrete
```






## Common Patterns {#common-patterns}



### Factory Pattern {#factory-pattern}


```typescript
async create(dto: CreateDTO): Promise<Entity> {
  const entity = this.repository.create(dto);
  entity.tenantId = RequestContext.currentTenantId();
  return this.repository.save(entity);
}
```


### Decorator Pattern {#decorator-pattern}


```typescript
@PermissionGuard(PermissionsEnum.EMPLOYEES_EDIT)
async update(id: string, dto: UpdateDTO): Promise<Entity> {
  return super.update(id, dto);
}
```


### Strategy Pattern (Multi-ORM) {#strategy-pattern-multi-orm}


```typescript
const strategy =
  this.configService.get("DB_ORM") === "mikroorm"
    ? new MikroOrmStrategy()
    : new TypeOrmStrategy();
```


## Related Pages {#related-pages}


- [Repository Pattern](https://sourcey-gauzy.pages.dev/architecture/repository-pattern/index.md) — data access
- [Request Lifecycle](https://sourcey-gauzy.pages.dev/architecture/request-lifecycle/index.md) — request flow
- [CQRS Pattern](https://sourcey-gauzy.pages.dev/architecture/cqrs-pattern/index.md) — CQRS
