@swoft/party-manager
v0.3.6
Published
## π― Overview
Maintainers
Readme
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
# From local Verdaccio registry
pnpm add @swoft/party-manager
# Or with npm
npm install @swoft/party-managerπ Quick Start
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
# 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=/metricsProgrammatic Configuration
import { getConfig } from '@swoft/party-manager';
const config = getConfig();
// Returns typed configuration objectπ API Documentation
ServiceFactory
The main entry point for all services:
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
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:
// 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:
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:
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
# 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:
pnpm analyzeπ οΈ Development
Building
# Build the package
pnpm build
# Watch mode
pnpm build:watch
# Type checking
pnpm checkArchitecture Decisions
This package was refactored using expert panel reviews to achieve enterprise-grade quality:
- No Dependency Injection Framework: Simple factory pattern instead of complex DI
- Minimal Exports: Only 2 export paths (main + contracts) for clean API
- Real Event Bus: Production pub/sub instead of mocks
- Comprehensive Error Handling: Typed errors with proper status codes
- Structured Logging: JSON/text formats with correlation IDs
See docs/EXPERT-PANEL-METHOD.md for the complete transformation story.
π Contracts
For TypeScript API contracts (Zodios):
import { partyManagerApi } from '@swoft/party-manager/contracts';π€ Contributing
- Follow DDD principles - keep domain logic in aggregates
- Maintain clean architecture boundaries
- Add tests for new features
- Update documentation
- 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
