@swoft/party-manager
Version:
321 lines (237 loc) โข 7.77 kB
Markdown
# 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