@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
222 lines (181 loc) ⢠8.45 kB
Markdown
# @dbs-portal/tool-mock
A comprehensive API mocking toolkit for the DBS Portal monorepo, built on top of Mock Service Worker (MSW). This package provides developer-friendly tools for creating reliable API simulations that accelerate development workflows without requiring backend services.
## š Features
### Core Capabilities
- **Environment-Aware Setup**: Automatically enables/disables based on environment (development, testing, production)
- **Type-Safe Mocking**: Full TypeScript support with existing API contracts and response types
- **Zero Configuration**: Works out-of-the-box with sensible defaults and automatic environment detection
- **Seamless Integration**: Built-in integration with @dbs-portal/core-api and @dbs-portal/core-auth packages
### Developer Experience
- **Easy API Switching**: Toggle between real APIs and mocked APIs with environment variables
- **CRUD Templates**: Pre-built handler factories for common CRUD operations
- **Data Factories**: Realistic mock data generation with customizable factories
- **Error Simulation**: Network conditions, timeouts, and error scenario testing
- **Hot Reloading**: Dynamic handler updates during development
### Build System Integration
- **Vite Plugin**: Seamless integration with Vite development server
- **Turborepo Support**: Optimized for monorepo build workflows
- **Service Worker Management**: Automatic MSW service worker setup and management
- **Development Server**: Built-in development server with MSW integration
### Testing & Quality
- **Testing Utilities**: Comprehensive test helpers and assertions
- **Storybook Integration**: Easy component development with mocked APIs
- **Performance Monitoring**: Request/response timing and performance metrics
- **Debug Tools**: Detailed logging and debugging capabilities
## šļø Architecture
### Package Structure
```
packages/tools/mock/
āāā src/
ā āāā core/ # Core MSW setup and configuration
ā āāā handlers/ # Handler factories and management
ā āāā factories/ # Mock data generation
ā āāā integration/ # Core package integrations
ā āāā build/ # Build system utilities
ā āāā testing/ # Testing utilities
ā āāā utils/ # Shared utilities
āāā templates/ # Template files and examples
āāā docs/ # Additional documentation
āāā examples/ # Usage examples
```
### Core Components
#### 1. Setup & Configuration
- **Environment Detection**: Automatic browser/Node.js environment detection
- **Configuration Management**: Centralized configuration with environment overrides
- **MSW Initialization**: Browser and Node.js MSW setup with proper lifecycle management
#### 2. Handler System
- **Handler Registry**: Centralized handler management with dynamic registration
- **Factory Functions**: Type-safe handler creation for common patterns
- **CRUD Handlers**: Pre-built handlers for Create, Read, Update, Delete operations
- **Auth Handlers**: Authentication and authorization mocking utilities
#### 3. Data Generation
- **Mock Factories**: Realistic data generation with customizable overrides
- **Response Builder**: Fluent API for building complex mock responses
- **Pagination Support**: Built-in pagination handling for list endpoints
- **Validation**: Request/response validation with schema support
#### 4. Integration Layer
- **API Client Integration**: Seamless integration with @dbs-portal/core-api
- **Auth Integration**: Authentication mocking with @dbs-portal/core-auth
- **React Query Support**: Optimized for TanStack Query workflows
- **Zustand Integration**: State management integration for mock data
## š ļø Usage Patterns
### Quick Start
```typescript
import { setupMocks, createCrudHandlers } from '@dbs-portal/tool-mock'
// Auto-setup based on environment
await setupMocks()
// Create CRUD handlers for a resource
const userHandlers = createCrudHandlers({
basePath: '/api/users',
dataFactory: (overrides = {}) => ({
id: generateId(),
email: 'user@example.com',
firstName: 'John',
lastName: 'Doe',
...overrides,
}),
})
```
### Environment Configuration
```bash
# Enable MSW in development
VITE_ENABLE_MOCKING=true
# Set mock mode
VITE_MOCK_MODE=development
# Configure response delay
VITE_MOCK_DELAY=300
# Enable detailed logging
VITE_MOCK_LOGGING=true
```
### Advanced Usage
```typescript
import {
createMockAwareApiClient,
createAuthHandlers,
mockResponseBuilder
} from '@dbs-portal/tool-mock'
// Create API client with MSW integration
const apiClient = await createMockAwareApiClient({
baseURL: '/api',
enableMocking: true,
mockHandlers: [
...createAuthHandlers('/api/auth'),
...createCrudHandlers({
basePath: '/api/products',
dataFactory: productFactory,
pagination: { defaultPageSize: 20 },
}),
],
})
// Custom response building
const customHandler = http.get('/api/custom', () => {
return mockResponseBuilder()
.data({ message: 'Custom response' })
.status(200)
.delay([100, 300])
.build()
})
```
## š§ Integration with Core Packages
### @dbs-portal/core-api Integration
- **HTTP Client Mocking**: Seamless integration with existing HTTP client
- **Request Interceptors**: Automatic request/response interception
- **Query Key Compatibility**: Maintains existing React Query key structures
- **Error Handling**: Consistent error handling with real API patterns
### @dbs-portal/core-auth Integration
- **Authentication Mocking**: JWT token simulation and validation
- **Authorization Testing**: Role and permission-based access control
- **Session Management**: Mock session lifecycle and token refresh
- **User Context**: Realistic user data and authentication state
## š¦ Monorepo Integration
### Package Dependencies
```json
{
"dependencies": {
"@dbs-portal/core-api": "workspace:*",
"@dbs-portal/core-auth": "workspace:*",
"@dbs-portal/core-shared": "workspace:*",
"msw": "^2.0.0"
}
}
```
### Build System
- **Turborepo Integration**: Optimized build caching and task dependencies
- **TypeScript Compilation**: Proper type generation and distribution
- **Vite Configuration**: Development and build optimization
- **Package Boundaries**: Strict import/export boundaries with other packages
### Development Workflow
1. **Package Installation**: Automatic MSW service worker setup
2. **Development Server**: Integrated with Vite dev server
3. **Hot Reloading**: Dynamic handler updates without restart
4. **Testing**: Seamless test environment setup
## šÆ Design Principles
### Developer-First
- **Minimal Configuration**: Works with zero setup for common use cases
- **Intuitive API**: Clear, discoverable API surface with TypeScript support
- **Fast Feedback**: Immediate visual feedback for API changes
- **Error Prevention**: Type safety and validation to prevent common mistakes
### Production-Ready
- **Performance**: Optimized for development speed without production impact
- **Reliability**: Robust error handling and graceful degradation
- **Security**: No production code inclusion and secure development practices
- **Maintainability**: Clean architecture and comprehensive documentation
### Extensible
- **Plugin System**: Extensible handler and factory system
- **Custom Integrations**: Easy integration with custom API patterns
- **Framework Agnostic**: Core utilities work with any frontend framework
- **Future-Proof**: Designed for easy updates and feature additions
## š Documentation Structure
- **README.md**: Overview and quick start guide
- **API.md**: Comprehensive API reference
- **INTEGRATION.md**: Integration guides for core packages
- **EXAMPLES.md**: Real-world usage examples
- **MIGRATION.md**: Migration guide from existing mocking solutions
- **TROUBLESHOOTING.md**: Common issues and solutions
## š¦ Getting Started
1. **Installation**: Package is automatically available in the monorepo
2. **Environment Setup**: Configure environment variables for your needs
3. **Basic Usage**: Start with auto-setup and default handlers
4. **Custom Handlers**: Add custom handlers for specific API endpoints
5. **Integration**: Integrate with existing API clients and authentication
See the [API documentation](./API.md) for detailed usage instructions and the [examples directory](./examples/) for real-world implementation patterns.