@dbs-portal/tool-mock
Version:
API mocking toolkit using MSW for DBS Portal development workflows
281 lines • 8.03 kB
JavaScript
/**
* Error simulation utilities
*/
import { HttpResponse } from 'msw';
import { getRandom } from '../factories/base';
/**
* Simulate errors based on configuration
*/
export function simulateError(url, method, config) {
if (!config) {
return null;
}
// Check network errors
if (config.networkErrorRate && getRandom() < config.networkErrorRate) {
return createNetworkErrorResponse();
}
// Check server errors
if (config.serverErrorRate && getRandom() < config.serverErrorRate) {
return createServerErrorResponse();
}
// Check timeout errors
if (config.timeoutErrorRate && getRandom() < config.timeoutErrorRate) {
return createTimeoutErrorResponse();
}
// Check custom errors
if (config.customErrors) {
for (const customError of config.customErrors) {
if (matchesPattern(url, customError.pattern) &&
(!customError.method || customError.method === method) &&
(!customError.probability || getRandom() < customError.probability)) {
const error = typeof customError.error === 'function'
? customError.error()
: customError.error;
return HttpResponse.json({
success: false,
error,
timestamp: new Date().toISOString(),
}, { status: error.status || 500 });
}
}
}
return null;
}
/**
* Create a network error response
*/
function createNetworkErrorResponse() {
return HttpResponse.json({
success: false,
error: {
code: 'NETWORK_ERROR',
message: 'Network request failed',
status: 0,
},
timestamp: new Date().toISOString(),
}, { status: 0 });
}
/**
* Create a server error response
*/
function createServerErrorResponse() {
const errors = [
{ code: 'INTERNAL_SERVER_ERROR', message: 'Internal server error', status: 500 },
{ code: 'BAD_GATEWAY', message: 'Bad gateway', status: 502 },
{ code: 'SERVICE_UNAVAILABLE', message: 'Service unavailable', status: 503 },
{ code: 'GATEWAY_TIMEOUT', message: 'Gateway timeout', status: 504 },
];
const error = errors[Math.floor(getRandom() * errors.length)];
return HttpResponse.json({
success: false,
error,
timestamp: new Date().toISOString(),
}, { status: error?.status || 500 });
}
/**
* Create a timeout error response
*/
function createTimeoutErrorResponse() {
return HttpResponse.json({
success: false,
error: {
code: 'TIMEOUT_ERROR',
message: 'Request timeout',
status: 408,
},
timestamp: new Date().toISOString(),
}, { status: 408 });
}
/**
* Check if URL matches a pattern
*/
function matchesPattern(url, pattern) {
if (typeof pattern === 'string') {
return url.includes(pattern);
}
return pattern.test(url);
}
/**
* Create custom error responses
*/
export const errorResponses = {
/**
* Create a validation error
*/
validation: (errors, message = 'Validation failed') => {
return HttpResponse.json({
success: false,
error: {
code: 'VALIDATION_ERROR',
message,
details: errors,
status: 400,
},
timestamp: new Date().toISOString(),
}, { status: 400 });
},
/**
* Create an unauthorized error
*/
unauthorized: (message = 'Unauthorized') => {
return HttpResponse.json({
success: false,
error: {
code: 'UNAUTHORIZED',
message,
status: 401,
},
timestamp: new Date().toISOString(),
}, { status: 401 });
},
/**
* Create a forbidden error
*/
forbidden: (message = 'Forbidden') => {
return HttpResponse.json({
success: false,
error: {
code: 'FORBIDDEN',
message,
status: 403,
},
timestamp: new Date().toISOString(),
}, { status: 403 });
},
/**
* Create a not found error
*/
notFound: (message = 'Resource not found') => {
return HttpResponse.json({
success: false,
error: {
code: 'NOT_FOUND',
message,
status: 404,
},
timestamp: new Date().toISOString(),
}, { status: 404 });
},
/**
* Create a conflict error
*/
conflict: (message = 'Resource conflict') => {
return HttpResponse.json({
success: false,
error: {
code: 'CONFLICT',
message,
status: 409,
},
timestamp: new Date().toISOString(),
}, { status: 409 });
},
/**
* Create a rate limit error
*/
rateLimit: (message = 'Rate limit exceeded', retryAfter = 60) => {
return HttpResponse.json({
success: false,
error: {
code: 'RATE_LIMIT_EXCEEDED',
message,
status: 429,
},
timestamp: new Date().toISOString(),
}, {
status: 429,
headers: {
'Retry-After': retryAfter.toString(),
},
});
},
/**
* Create a server error
*/
serverError: (message = 'Internal server error') => {
return HttpResponse.json({
success: false,
error: {
code: 'INTERNAL_SERVER_ERROR',
message,
status: 500,
},
timestamp: new Date().toISOString(),
}, { status: 500 });
},
/**
* Create a custom error
*/
custom: (code, message, status, details) => {
return HttpResponse.json({
success: false,
error: {
code,
message,
status,
details,
},
timestamp: new Date().toISOString(),
}, { status });
},
};
/**
* Error probability calculator
*/
export function calculateErrorProbability(baseRate, factors = {}) {
let probability = baseRate;
// Increase errors during peak hours (9-17)
if (factors.timeOfDay !== undefined) {
if (factors.timeOfDay >= 9 && factors.timeOfDay <= 17) {
probability *= 1.5;
}
}
// Increase errors on weekdays
if (factors.dayOfWeek !== undefined) {
if (factors.dayOfWeek >= 1 && factors.dayOfWeek <= 5) {
probability *= 1.2;
}
}
// Increase errors with high load
if (factors.load !== undefined) {
probability *= (1 + factors.load);
}
return Math.min(probability, 1);
}
/**
* Create error simulation based on environment
*/
export function createEnvironmentErrorSimulation(environment) {
switch (environment) {
case 'development':
return {
networkErrorRate: 0.02,
serverErrorRate: 0.01,
timeoutErrorRate: 0.005,
customErrors: [],
};
case 'testing':
return {
networkErrorRate: 0,
serverErrorRate: 0,
timeoutErrorRate: 0,
customErrors: [],
};
case 'staging':
return {
networkErrorRate: 0.01,
serverErrorRate: 0.005,
timeoutErrorRate: 0.002,
customErrors: [],
};
case 'production':
default:
return {
networkErrorRate: 0,
serverErrorRate: 0,
timeoutErrorRate: 0,
customErrors: [],
};
}
}
//# sourceMappingURL=error.js.map