Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active March 23, 2021 16:05
Show Gist options
  • Save smitroshin/4a54884388b808941b4dd2d617141f5c to your computer and use it in GitHub Desktop.
Save smitroshin/4a54884388b808941b4dd2d617141f5c to your computer and use it in GitHub Desktop.
Tool for simulation of http requests
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