UNPKG

@dbs-portal/tool-mock

Version:

API mocking toolkit using MSW for DBS Portal development workflows

90 lines 2.52 kB
/** * Delay utilities for simulating network latency */ import { getRandom } from '../factories/base'; /** * Apply delay to simulate network latency */ export async function applyDelay(delay) { if (delay === 0) { return; } let delayMs; if (Array.isArray(delay)) { const [min, max] = delay; delayMs = min + getRandom() * (max - min); } else { delayMs = delay; } if (delayMs > 0) { await new Promise(resolve => setTimeout(resolve, delayMs)); } } /** * Create a delay function with specific options */ export function createDelayFunction(defaultDelay) { return async (customDelay) => { const delay = customDelay ?? defaultDelay; await applyDelay(delay); }; } /** * Simulate progressive delay (increases over time) */ export async function applyProgressiveDelay(baseDelay, multiplier = 1.5, maxDelay = 5000) { let currentDelay; if (Array.isArray(baseDelay)) { const [min, max] = baseDelay; currentDelay = min + getRandom() * (max - min); } else { currentDelay = baseDelay; } currentDelay = Math.min(currentDelay * multiplier, maxDelay); if (currentDelay > 0) { await new Promise(resolve => setTimeout(resolve, currentDelay)); } } /** * Simulate network jitter */ export async function applyJitteredDelay(baseDelay, jitterPercent = 0.1) { const jitter = baseDelay * jitterPercent; const actualDelay = baseDelay + (getRandom() - 0.5) * 2 * jitter; if (actualDelay > 0) { await new Promise(resolve => setTimeout(resolve, actualDelay)); } } /** * Simulate connection-based delays */ export async function applyConnectionDelay(connection = 'fast') { switch (connection) { case 'fast': await applyDelay([10, 50]); break; case 'slow': await applyDelay([2000, 5000]); break; case 'unstable': await applyDelay([100, 3000]); break; case 'offline': throw new Error('Network offline'); default: await applyDelay([100, 300]); } } /** * Delay with timeout */ export async function applyDelayWithTimeout(delay, timeout) { const delayPromise = applyDelay(delay); const timeoutPromise = new Promise((_, reject) => { setTimeout(() => reject(new Error('Delay timeout')), timeout); }); await Promise.race([delayPromise, timeoutPromise]); } //# sourceMappingURL=delay.js.map