response.js
1.22 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
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* HTTP Response.
*/
import Headers from './headers';
import Promise from '../promise';
import { when, isBlob, isString } from '../util';
export default class Response {
constructor(body, {url, headers, status, statusText}) {
this.url = url;
this.ok = status >= 200 && status < 300;
this.status = status || 0;
this.statusText = statusText || '';
this.headers = new Headers(headers);
this.body = body;
if (isString(body)) {
this.bodyText = body;
} else if (isBlob(body)) {
this.bodyBlob = body;
if (isBlobText(body)) {
this.bodyText = blobText(body);
}
}
}
blob() {
return when(this.bodyBlob);
}
text() {
return when(this.bodyText);
}
json() {
return when(this.text(), text => JSON.parse(text));
}
}
function blobText(body) {
return new Promise((resolve) => {
var reader = new FileReader();
reader.readAsText(body);
reader.onload = () => {
resolve(reader.result);
};
});
}
function isBlobText(body) {
return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1;
}