npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@dbs-portal/tool-mock

v1.0.2

Published

API mocking toolkit using MSW for DBS Portal development workflows

Readme

@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

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: '[email protected]',
    firstName: 'John',
    lastName: 'Doe',
    ...overrides,
  }),
})

Environment Configuration

# 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

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

{
  "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 for detailed usage instructions and the examples directory for real-world implementation patterns.