-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.js
47 lines (40 loc) · 1.21 KB
/
backend.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
(function () {
var UPLOAD_URL = 'https://js.dump.academy/kekstagram';
var DOWNLOAD_URL = UPLOAD_URL + '/data';
var TIMEOUT = 10000;
var SUCCESS_CODE = 200;
var createXHR = function (onLoad, onError) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener('load', function () {
if (xhr.status === SUCCESS_CODE) {
onLoad(xhr.response);
} else {
onError('Статус ответа: ' + xhr.status + ' ' + xhr.statusText);
}
});
xhr.addEventListener('error', function () {
onError('Произошла ошибка соединения');
});
xhr.addEventListener('timeout', function () {
onError('Запрос не успел выполниться за ' + xhr.timeout + 'мс');
});
xhr.timeout = TIMEOUT;
return xhr;
};
var download = function (onLoad, onError) {
var xhr = createXHR(onLoad, onError);
xhr.open('GET', DOWNLOAD_URL);
xhr.send();
};
var upload = function (data, onLoad, onError) {
var xhr = createXHR(onLoad, onError);
xhr.open('POST', UPLOAD_URL);
xhr.send(data);
};
window.backend = {
download: download,
upload: upload
};
})();