frontexpress/lib/requester.js

113 lines
3.3 KiB
JavaScript
Raw Normal View History

2016-07-15 19:34:24 +00:00
/**
* Module dependencies.
* @private
*/
2016-06-26 10:10:37 +00:00
export default class Requester {
2016-07-15 19:34:24 +00:00
/**
* Make an ajax request.
*
* @param {Object} request
* @param {Function} success callback
* @param {Function} failure callback
* @private
*/
2016-07-23 10:31:40 +00:00
fetch(request, resolve, reject) {
const {method, uri, headers, data} = request;
2016-07-23 10:31:40 +00:00
2016-06-26 10:10:37 +00:00
const success = (responseText) => {
resolve(
2016-07-23 10:31:40 +00:00
request,
{
status: 200,
statusText: 'OK',
responseText
}
2016-06-26 10:10:37 +00:00
);
};
const fail = ({status, statusText, errorThrown}) => {
// Removed for reducing size of frontexpress
// const errors = this._analyzeErrors({status, statusText, errorThrown});
2016-06-26 10:10:37 +00:00
reject(
2016-07-23 10:31:40 +00:00
request,
{
status,
statusText,
errorThrown,
errors: `HTTP ${status} ${statusText?statusText:''}`
}
2016-06-26 10:10:37 +00:00
);
};
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
success(xmlhttp.responseText);
} else {
fail({status: xmlhttp.status, statusText: xmlhttp.statusText});
}
}
};
try {
xmlhttp.open(method, uri, true);
if (headers) {
for (const header of Object.keys(headers)) {
xmlhttp.setRequestHeader(header, headers[header]);
}
}
if (data) {
xmlhttp.send(data);
2016-06-26 10:10:37 +00:00
} else {
xmlhttp.send();
}
} catch (errorThrown) {
fail({errorThrown});
}
}
// Removed for reducing size of frontexpress
// /**
// * Analyse response errors.
// *
// * @private
// */
2016-07-15 19:34:24 +00:00
// _analyzeErrors(response) {
// // manage exceptions
// if (response.errorThrown) {
// if (response.errorThrown.name === 'SyntaxError') {
// return 'Problem during data decoding [JSON]';
// }
// if (response.errorThrown.name === 'TimeoutError') {
// return 'Server is taking too long to reply';
// }
// if (response.errorThrown.name === 'AbortError') {
// return 'Request cancelled on server';
// }
// if (response.errorThrown.name === 'NetworkError') {
// return 'A network error occurred';
// }
// throw response.errorThrown;
// }
2016-07-15 19:34:24 +00:00
// // manage status
// if (response.status === 0) {
// return 'Server access problem. Check your network connection';
// }
// if (response.status === 401) {
// return 'Your session has expired, Please reconnect. [code: 401]';
// }
// if (response.status === 404) {
// return 'Page not found on server. [code: 404]';
// }
// if (response.status === 500) {
// return 'Internal server error. [code: 500]';
// }
// return `Unknown error. ${response.statusText?response.statusText:''}`;
// }
}