http-handler.js
1.21 KB
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
48
49
50
var window = require('global/window');
const httpResponseHandler = (callback, decodeResponseBody = false) => (err, response, responseBody) => {
// if the XHR failed, return that error
if (err) {
callback(err);
return;
}
// if the HTTP status code is 4xx or 5xx, the request also failed
if (response.statusCode >= 400 && response.statusCode <= 599) {
let cause = responseBody;
if (decodeResponseBody) {
if (window.TextDecoder) {
const charset = getCharset(response.headers && response.headers['content-type']);
try {
cause = new TextDecoder(charset).decode(responseBody);
} catch (e) {
}
} else {
cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
}
}
callback({cause});
return;
}
// otherwise, request succeeded
callback(null, responseBody);
};
function getCharset(contentTypeHeader = '') {
return contentTypeHeader
.toLowerCase()
.split(';')
.reduce((charset, contentType) => {
const [type, value] = contentType.split('=');
if (type.trim() === 'charset') {
return value.trim();
}
return charset;
}, 'utf-8');
}
module.exports = httpResponseHandler;