UNPKG

express-chaos-middleware

Version:
101 lines 3.06 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Rules = exports.chaos = void 0; const debug_1 = __importDefault(require("debug")); const seedrandom_1 = __importDefault(require("seedrandom")); const debug = (0, debug_1.default)("express-chaos-middleware"); const Rules = { DELAY: delay, HTTPERROR: httpError, EXCEPTION: exception, }; exports.Rules = Rules; /** * Generate alphanumeric seed * @param length - seed length * @returns seed */ function generateSeed(length) { var result = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } /** * Wait X ms * @param ms - waiting time */ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); /** * Requests slowdown * @param req - express request * @param res - express response * @param next - express next function */ async function delay(req, res, next) { const maxDelay = req.options?.maxDelay || 500; const pause = Math.floor(req.options.rng() * maxDelay); debug(`rulesFunctions.delay - wait ${pause} ms`); await wait(pause); next(); } /** * Random response error * @param req - express request * @param res - express response */ function httpError(req, res) { const errCodes = req.options?.errCodes || [400, 401, 403, 404, 409, 500]; const code = errCodes[Math.floor(req.options.rng() * errCodes.length)]; debug(`rulesFunctions.httpError - send ${code} code`); res.status(code); res.end(); } /** * Throw random exception */ function exception() { debug(`rulesFunctions.exception - throw exception`); throw new Error("BOOM !"); } /** * Randomly throw error and slow response * @param options - user options * @returns a chaos middleware instance */ function chaos(options) { const seed = options?.seed || generateSeed(15); debug(`current seed ${seed}`); const rng = (0, seedrandom_1.default)(seed); const chaosOptions = { ...options, seed, rng, }; const probability = chaosOptions?.probability || 10; if (!Number.isInteger(probability) || probability < 0 || probability > 100) { throw new Error("Invalid probability value"); } const rules = chaosOptions?.rules || [ Rules.DELAY, Rules.HTTPERROR, Rules.EXCEPTION, ]; return (req, res, next) => { req.options = chaosOptions; const rand = Math.floor(chaosOptions.rng() * 100); if (rand <= probability) { const rule = rules[Math.floor(chaosOptions.rng() * rules.length)]; return rule(req, res, next); } return next(); }; } exports.chaos = chaos; //# sourceMappingURL=index.js.map