@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
154 lines • 3.26 kB
JavaScript
/**
* Handler manager for dynamic handler management
*/
import { getMswInstance } from '../core/setup';
/**
* Implementation of handler manager
*/
export class MockHandlerManager {
handlers = new Set();
enabled = true;
/**
* Add handlers
*/
add(...handlers) {
for (const handler of handlers) {
this.handlers.add(handler);
}
if (this.enabled) {
this.applyHandlers();
}
}
/**
* Remove handlers
*/
remove(...handlers) {
for (const handler of handlers) {
this.handlers.delete(handler);
}
if (this.enabled) {
this.applyHandlers();
}
}
/**
* Replace all handlers
*/
replace(handlers) {
this.handlers.clear();
for (const handler of handlers) {
this.handlers.add(handler);
}
if (this.enabled) {
this.applyHandlers();
}
}
/**
* Get current handlers
*/
getHandlers() {
return Array.from(this.handlers);
}
/**
* Enable/disable handlers
*/
setEnabled(enabled) {
this.enabled = enabled;
this.applyHandlers();
}
/**
* Check if enabled
*/
isEnabled() {
return this.enabled;
}
/**
* Apply handlers to MSW instance
*/
applyHandlers() {
const instance = getMswInstance();
if (!instance) {
console.warn('MSW instance not available, cannot apply handlers');
return;
}
if (this.enabled) {
instance.resetHandlers(...this.getHandlers());
}
else {
instance.resetHandlers();
}
}
/**
* Clear all handlers
*/
clear() {
this.handlers.clear();
if (this.enabled) {
this.applyHandlers();
}
}
/**
* Get handler count
*/
getHandlerCount() {
return this.handlers.size;
}
/**
* Check if handler exists
*/
hasHandler(handler) {
return this.handlers.has(handler);
}
}
/**
* Global handler manager instance
*/
export const globalHandlerManager = new MockHandlerManager();
/**
* Add handlers globally
*/
export function addHandlers(...handlers) {
globalHandlerManager.add(...handlers);
}
/**
* Remove handlers globally
*/
export function removeHandlers(...handlers) {
globalHandlerManager.remove(...handlers);
}
/**
* Replace all handlers globally
*/
export function replaceHandlers(handlers) {
globalHandlerManager.replace(handlers);
}
/**
* Get current handlers
*/
export function getCurrentHandlers() {
return globalHandlerManager.getHandlers();
}
/**
* Enable/disable handler management
*/
export function setHandlersEnabled(enabled) {
globalHandlerManager.setEnabled(enabled);
}
/**
* Check if handlers are enabled
*/
export function areHandlersEnabled() {
return globalHandlerManager.isEnabled();
}
/**
* Clear all handlers
*/
export function clearHandlers() {
globalHandlerManager.clear();
}
/**
* Create a scoped handler manager
*/
export function createHandlerManager() {
return new MockHandlerManager();
}
//# sourceMappingURL=manager.js.map