frontexpress/lib/requester.js

79 lines
2.6 KiB
JavaScript
Raw Normal View History

2016-06-26 10:10:37 +00:00
export default class Requester {
fetch({method, uri, headers, data}, resolve, reject) {
2016-06-26 10:10:37 +00:00
const success = (responseText) => {
resolve(
{method, uri, headers, data},
2016-06-26 10:10:37 +00:00
{status: 200, statusText: 'OK', responseText}
);
};
const fail = ({status, statusText, errorThrown}) => {
const errors = this._analyzeErrors({status, statusText, errorThrown});
reject(
{method, uri, headers, data},
2016-06-26 10:10:37 +00:00
{status, statusText, errorThrown, errors}
);
};
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});
}
}
_analyzeErrors(response) {
2016-07-14 13:14:16 +00:00
// manage exceptions
if (response.errorThrown) {
2016-06-26 10:10:37 +00:00
if (response.errorThrown.name === 'SyntaxError') {
2016-07-14 13:14:16 +00:00
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';
2016-06-26 10:10:37 +00:00
}
2016-07-14 13:14:16 +00:00
throw response.errorThrown;
}
// 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]';
2016-06-26 10:10:37 +00:00
}
2016-07-14 13:14:16 +00:00
return `Unknown error. ${response.statusText?response.statusText:''}`;
2016-06-26 10:10:37 +00:00
}
}