UNPKG

@swoft/party-manager

Version:
321 lines (237 loc) โ€ข 7.77 kB
# Party Manager Domain Package ## ๐ŸŽฏ Overview Enterprise-grade TypeScript package for party (person, organization, team) management following Domain-Driven Design principles. This package provides authentication, user management, and organizational structure capabilities with production-ready error handling, logging, and monitoring. ## โœจ Features - **Authentication & Authorization**: Secure login, session management, password recovery - **Person Management**: User profiles, contact information, organizational associations - **Organization Management**: Company structures, hierarchies, departments - **Team Management**: Team creation, member management, leadership assignment - **Production-Ready**: Comprehensive error handling, structured logging, health checks - **Event-Driven**: Real event bus with pub/sub for domain events - **Type-Safe**: Full TypeScript with strict type checking ## ๐Ÿ“ฆ Installation ```bash # From local Verdaccio registry pnpm add @swoft/party-manager # Or with npm npm install @swoft/party-manager ``` ## ๐Ÿš€ Quick Start ```typescript import { ServiceFactory, DomainEventBuilder } from '@swoft/party-manager'; // Initialize the service factory const factory = ServiceFactory.getInstance(); await factory.initialize(); // Get EventBus (the working component) const eventBus = factory.getEventBus(); // Subscribe to domain events eventBus.subscribe('UserAction', async (event) => { console.log('Event:', event.eventType, 'for', event.aggregateId); }); // Publish events await eventBus.publish( DomainEventBuilder.create('UserAction', 'user-123', { action: 'login', timestamp: new Date() }) ); // Health check const health = await factory.getHealthStatus(); console.log('System healthy:', health.healthy); console.log('Database:', health.database); // Graceful shutdown await factory.shutdown(); ``` ## ๐Ÿ—๏ธ Architecture This package follows Domain-Driven Design (DDD) principles with clean architecture: ``` src/ โ”œโ”€โ”€ bounded-contexts/ # Domain boundaries โ”‚ โ”œโ”€โ”€ authentication/ # Login, sessions, passwords โ”‚ โ”‚ โ”œโ”€โ”€ domain/ # Aggregates, value objects โ”‚ โ”‚ โ””โ”€โ”€ application/ # Use case services โ”‚ โ””โ”€โ”€ parties/ # People, orgs, teams โ”‚ โ”œโ”€โ”€ domain/ # Rich domain models โ”‚ โ””โ”€โ”€ application/ # Business operations โ”œโ”€โ”€ infrastructure/ # Technical implementations โ”‚ โ”œโ”€โ”€ factory/ # Simple service factory (no DI) โ”‚ โ”œโ”€โ”€ repositories/ # MongoDB implementations โ”‚ โ”œโ”€โ”€ events/ # Event bus implementation โ”‚ โ”œโ”€โ”€ logging/ # Structured logging โ”‚ โ”œโ”€โ”€ errors/ # Error types & handling โ”‚ โ””โ”€โ”€ health/ # Health monitoring โ””โ”€โ”€ config/ # Environment configuration ``` ## ๐Ÿ”ง Configuration ### Environment Variables ```bash # MongoDB Configuration PARTY_MANAGER_MONGO_URL=mongodb://localhost:27017 PARTY_MANAGER_DB_NAME=party_manager MONGO_MAX_POOL_SIZE=10 MONGO_MIN_POOL_SIZE=2 # Logging LOG_LEVEL=info # error | warn | info | debug LOG_FORMAT=json # json | text # Health Checks HEALTH_CHECK_ENABLED=true HEALTH_CHECK_PATH=/health # Metrics (optional) METRICS_ENABLED=false METRICS_PATH=/metrics ``` ### Programmatic Configuration ```typescript import { getConfig } from '@swoft/party-manager'; const config = getConfig(); // Returns typed configuration object ``` ## ๐Ÿ“š API Documentation ### ServiceFactory The main entry point for all services: ```typescript const factory = ServiceFactory.getInstance(); // Initialize (required once) await factory.initialize(); // Get services factory.getAuthenticationService() factory.getRegistrationService() factory.getPasswordService() factory.getPersonRepository() factory.getOrganisationRepository() factory.getTeamRepository() factory.getEventBus() // Health monitoring await factory.getHealthStatus() // Cleanup await factory.shutdown() ``` ### Authentication Service ```typescript interface LoginCommand { email: string; password: string; rememberMe: boolean; ipAddress?: string; userAgent?: string; } const result = await authService.login(command); await authService.logout(sessionId); await authService.validateSession(sessionId); ``` ### Event Bus Production-ready event system with pub/sub: ```typescript // Subscribe to events const subscription = eventBus.subscribe('UserLoggedIn', async (event) => { // Handle event }); // Unsubscribe subscription.unsubscribe(); // Subscribe to all events eventBus.subscribeToAll(async (event) => { console.log('Event:', event.eventType); }); // Get statistics const stats = eventBus.getStats(); ``` ### Error Handling Comprehensive error types with HTTP status codes: ```typescript import { InvalidCredentialsError, AccountLockedError, PersonNotFoundError, DatabaseError, ErrorHandler } from '@swoft/party-manager'; try { await authService.login(command); } catch (error) { if (error instanceof InvalidCredentialsError) { // Handle invalid credentials (401) } else if (error instanceof AccountLockedError) { // Handle locked account (403) } // Get HTTP status code const statusCode = ErrorHandler.getHttpStatusCode(error); // Format for API response const response = ErrorHandler.formatErrorResponse(error); } ``` ### Logging Structured logging with correlation IDs: ```typescript import { Logger, LogLevel } from '@swoft/party-manager'; const logger = Logger.getInstance(); // Log with context logger.info('Operation completed', { userId: '123', correlationId: 'abc-def', duration: 150 }); // Create child logger with fixed context const serviceLogger = logger.child({ service: 'AuthService' }); serviceLogger.error('Authentication failed', error); ``` ## ๐Ÿงช Testing ```bash # Run tests pnpm test # With coverage pnpm test:coverage # Watch mode pnpm test:watch ``` ## ๐Ÿ“Š Bundle Size Limits The package enforces strict size limits to prevent bloat: - Main API Bundle: < 80 KB - ESM Bundle: < 65 KB - Contracts Bundle: < 35 KB - Contracts ESM: < 25 KB Check current sizes: ```bash pnpm analyze ``` ## ๐Ÿ› ๏ธ Development ### Building ```bash # Build the package pnpm build # Watch mode pnpm build:watch # Type checking pnpm check ``` ### Architecture Decisions This package was refactored using expert panel reviews to achieve enterprise-grade quality: 1. **No Dependency Injection Framework**: Simple factory pattern instead of complex DI 2. **Minimal Exports**: Only 2 export paths (main + contracts) for clean API 3. **Real Event Bus**: Production pub/sub instead of mocks 4. **Comprehensive Error Handling**: Typed errors with proper status codes 5. **Structured Logging**: JSON/text formats with correlation IDs See [docs/EXPERT-PANEL-METHOD.md](docs/EXPERT-PANEL-METHOD.md) for the complete transformation story. ## ๐Ÿ“ Contracts For TypeScript API contracts (Zodios): ```typescript import { partyManagerApi } from '@swoft/party-manager/contracts'; ``` ## ๐Ÿค Contributing 1. Follow DDD principles - keep domain logic in aggregates 2. Maintain clean architecture boundaries 3. Add tests for new features 4. Update documentation 5. Respect size limits ## ๐Ÿ“„ License MIT ## ๐Ÿ† Credits Refactored to enterprise-grade quality through expert panel methodology featuring insights from: - Eric Evans (Domain-Driven Design) - Vaughn Vernon (Implementing DDD) - Martin Fowler (Enterprise Architecture) - Michel Weststrate (MobX, TypeScript) - Kamil Mysliwiec (NestJS) - Jared Palmer (Turborepo) - Ben Awad (Production TypeScript) --- Built with โค๏ธ using Domain-Driven Design principles