# Metaverse Service Modular Pattern

The metaverse service is organized around domain slices with clear boundaries
and shared infrastructure. Use this pattern when refactoring large services.

## Layout

- `domains/<domain>/`
  - `application/` — use cases/orchestrators (no HTTP concerns)
  - `domain/` — entities/value objects/services with invariants and pure logic
  - `infrastructure/` — adapters (persistence, external APIs, caches, queues)
  - `__tests__/` — domain + application tests for the slice
- `adapters/` — transport adapters (HTTP/WebSocket/GraphQL) that delegate to
  application layer
- `plugins/` — cross-cutting Fastify plugins (auth, tracing, input validation)
- `config/` — config loaders and type-safe settings
- `shared/` — shared utilities used across domains (no cross-domain coupling)
- `__tests__/integration/` — integration tests across adapters/domains

## Migration Steps for Large Services

1. **Slice domains**: identify 3–7 bounded contexts (e.g., auth, billing,
   content). Create `domains/<domain>/` folders and move pure logic there first.
2. **Extract application layer**: wrap workflows/use-cases in `application/` (no
   HTTP types). Keep handlers thin.
3. **Adapter isolation**: move HTTP/WebSocket handlers to `adapters/` and map
   requests to application commands/queries.
4. **Shared plugins**: reuse `services/common/server-template` and
   `services/lib` middleware instead of per-domain middleware copies.
5. **Testing**: mirror structure—unit tests inside each domain; integration
   tests under `__tests__/integration/` hitting adapters.
6. **Contracts**: keep request/response/DTO types near adapters; domain models
   stay internal and are not exported to transports.
7. **Cross-domain communication**: depend on interfaces, not implementations.
   Compose at the application layer; avoid direct imports between domain
   folders.

## Adoption Targets

- Start with large multi-team services (BFF, auth, content, conversation).
- Apply incrementally: move one domain at a time, keeping existing routes
  delegating to new application/domain functions.
- Maintain existing tests; add adapter tests as routes are re-homed.

## Definition of Done for a Migrated Domain

- Domain logic lives in `domains/<domain>/domain/`.
- Use-cases live in `domains/<domain>/application/`.
- HTTP adapters delegate to use-cases only.
- Cross-cutting middleware uses shared plugins; no duplicate setup code.
- Domain tests are colocated; integration tests cover adapters.
