@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
245 lines • 6.67 kB
JavaScript
/**
* Main MSW setup and lifecycle management
*/
import { getMockConfig, createConfigFromSetupOptions } from './config';
// Re-export for integration modules
export { getMockConfig } from './config';
import { getEnvironmentInfo } from './environment';
import { setupBrowser } from './browser';
/**
* Global MSW instance references
*/
let currentInstance = null;
let isSetup = false;
/**
* Setup MSW based on environment with automatic detection
*/
export async function setupMocks(options = {}) {
// Prevent double setup
if (isSetup) {
console.warn('MSW is already set up');
return;
}
// Create configuration from options
const config = createConfigFromSetupOptions(options);
// Check if mocking should be enabled
if (!config.enabled) {
if (config.logging) {
console.log('MSW: Mocking is disabled');
}
return;
}
const envInfo = getEnvironmentInfo();
if (config.logging) {
console.log(`MSW: Setting up in ${envInfo.environment} environment (${config.mode} mode)`);
}
// Collect all handlers
const allHandlers = [
...(config.handlers || []),
...(options.handlers || []),
];
try {
// Setup based on environment
if (envInfo.environment === 'browser') {
currentInstance = await setupBrowser(allHandlers, config);
if (options.start !== false) {
await currentInstance.start({
onUnhandledRequest: config.mode === 'development' ? 'warn' : 'bypass',
quiet: !config.logging,
});
}
}
else if (envInfo.environment === 'node') {
// Dynamic import to avoid bundling Node.js code in browser builds
const { setupNodeServer } = await import('./server');
currentInstance = setupNodeServer(allHandlers, config);
if (options.start !== false) {
await currentInstance.start({
onUnhandledRequest: config.mode === 'testing' ? 'error' : 'warn',
});
}
}
else {
throw new Error(`Unsupported environment: ${envInfo.environment}`);
}
isSetup = true;
if (config.logging) {
console.log(`MSW: Successfully set up with ${allHandlers.length} handlers`);
}
}
catch (error) {
console.error('MSW: Failed to setup:', error);
throw error;
}
}
/**
* Teardown MSW and clean up resources
*/
export async function teardownMocks() {
if (!isSetup || !currentInstance) {
return;
}
const config = getMockConfig();
try {
currentInstance.stop();
currentInstance = null;
isSetup = false;
if (config.logging) {
console.log('MSW: Successfully torn down');
}
}
catch (error) {
console.error('MSW: Failed to teardown:', error);
throw error;
}
}
/**
* Restart MSW with new configuration
*/
export async function restartMocks(options = {}) {
await teardownMocks();
await setupMocks(options);
}
/**
* Add handlers to existing MSW instance
*/
export function addCoreHandlers(...handlers) {
if (!isSetup || !currentInstance) {
console.warn('MSW: Cannot add handlers - MSW is not set up');
return;
}
currentInstance.use(...handlers);
const config = getMockConfig();
if (config.logging) {
console.log(`MSW: Added ${handlers.length} handlers`);
}
}
/**
* Reset handlers to original state
*/
export function resetHandlers(...handlers) {
if (!isSetup || !currentInstance) {
console.warn('MSW: Cannot reset handlers - MSW is not set up');
return;
}
currentInstance.resetHandlers(...handlers);
const config = getMockConfig();
if (config.logging) {
console.log('MSW: Reset handlers to original state');
}
}
/**
* Restore original handlers
*/
export function restoreHandlers() {
if (!isSetup || !currentInstance) {
console.warn('MSW: Cannot restore handlers - MSW is not set up');
return;
}
currentInstance.restoreHandlers();
const config = getMockConfig();
if (config.logging) {
console.log('MSW: Restored original handlers');
}
}
/**
* Check if MSW is set up and running
*/
export function isMswSetup() {
return isSetup && currentInstance !== null;
}
/**
* Check if MSW is currently running
*/
export function isMswRunning() {
return isSetup && currentInstance !== null && currentInstance.isRunning();
}
/**
* Get current MSW instance
*/
export function getMswInstance() {
return currentInstance;
}
/**
* Auto-setup MSW based on environment (convenience function)
*/
export async function autoSetupMocks(customHandlers = []) {
const envInfo = getEnvironmentInfo();
if (!envInfo.shouldMock) {
return;
}
await setupMocks({
handlers: customHandlers,
start: true,
});
}
/**
* Setup MSW for development environment
*/
export async function setupDevelopmentMocks(handlers = []) {
await setupMocks({
config: {
enabled: true,
mode: 'development',
logging: true,
delay: [100, 300],
errorSimulation: {
networkErrorRate: 0.01,
serverErrorRate: 0.005,
},
},
handlers,
start: true,
});
}
/**
* Setup MSW for testing environment
*/
export async function setupTestingMocks(handlers = []) {
await setupMocks({
config: {
enabled: true,
mode: 'testing',
logging: false,
delay: 0,
errorSimulation: {
networkErrorRate: 0,
serverErrorRate: 0,
},
},
handlers,
start: true,
});
}
/**
* Setup MSW for Storybook environment
*/
export async function setupStorybookMocks(handlers = []) {
await setupMocks({
config: {
enabled: true,
mode: 'storybook',
logging: false,
delay: [50, 150],
errorSimulation: {
networkErrorRate: 0,
serverErrorRate: 0,
},
},
handlers,
start: true,
});
}
/**
* Get setup status information
*/
export function getSetupStatus() {
return {
isSetup,
isRunning: isMswRunning(),
hasInstance: currentInstance !== null,
config: isSetup ? getMockConfig() : null,
environment: getEnvironmentInfo(),
};
}
//# sourceMappingURL=setup.js.map