Last active
March 23, 2021 16:05
-
-
Save smitroshin/4a54884388b808941b4dd2d617141f5c to your computer and use it in GitHub Desktop.
Tool for simulation of http requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const randomInteger = (min, max) => | |
Math.floor(Math.random() * (max - min + 1)) + min; | |
const randomBoolean = () => Math.random() >= 0.5; | |
const defaultTime = () => randomInteger(1000, 3000); | |
/** | |
* Tool for simulating http requests | |
* | |
* @class RequestSimulator | |
*/ | |
export default class RequestSimulator { | |
/** | |
* Request with successful response | |
* | |
* @method success | |
* @param {*} data | |
* @param {Number} time | |
* @returns {Promise} | |
*/ | |
static success(data = 'success', time = defaultTime()) { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve(data), time); | |
}); | |
} | |
/** | |
* Request with rejected response | |
* | |
* @method error | |
* @param {*} data | |
* @param {Number} time | |
* @returns {Promise} | |
*/ | |
static error(data = 'error', time = defaultTime()) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => reject(new Error(data)), time); | |
}); | |
} | |
/** | |
* Request with random response | |
* | |
* @method random | |
* @param {*} sData | |
* @param {*} eData | |
* @param {Number} time | |
* @returns {Promise} | |
*/ | |
static random(sData = 'success', eData = 'error', time = defaultTime()) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (randomBoolean()) return resolve(sData); | |
return reject(new Error(eData)); | |
}, time); | |
}); | |
} | |
} | |
RequestSimulator.success(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment