-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeq.js
More file actions
86 lines (63 loc) · 2.21 KB
/
Copy pathfeq.js
File metadata and controls
86 lines (63 loc) · 2.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import fetch from "isomorphic-fetch";
export default class Feq {
constructor({headers = {}, requestProcessors = [], responseProcessors = []} = {}) {
this.options = {};
this.options.headers = headers;
this.options.mode = "cors";
this.requestProcessors = requestProcessors;
this.responseProcessors = responseProcessors;
Object.freeze(this.options);
}
send({method, url, body, options} = {}) {
const plainRequest = {method};
const headers = {};
if (body) plainRequest.body = body;
Object.assign(plainRequest, this.options);
Object.assign(headers, this.options.headers);
if (options) {
if (options.headers) Object.assign(headers, options.headers);
Object.assign(plainResponse, options);
}
plainRequest.headers = headers;
this.requestProcessors.forEach(processor => processor(plainRequest));
return Feq.fetch(url, plainRequest)
.then(response => {
const plainResponse = {};
[
"ok", "url", "type", "status", "statusText"
].forEach(prop => plainResponse[prop] = response[prop]);
plainResponse.headers = response.headers;
const contentType = plainResponse.headers.get("Content-Type") || "";
const bodyPromise = contentType.includes("/json") ?
response.json() :
(contentType.includes("text/") ? response.text() : response.blob());
return Promise.all([plainResponse, bodyPromise]);
})
.then(array => {
const plainResponse = array[0];
const body = array[1];
plainResponse.body = body;
return plainResponse;
})
.then(response => {
this.responseProcessors.forEach(processor => processor(response));
return response;
});
}
get(url, options) {
return this.send({method: "GET", url, options});
}
delete(url, options) {
return this.send({method: "DELETE", url, options});
}
post(url, body, options) {
return this.send({method: "POST", url, body, options});
}
put(url, body, options) {
return this.send({method: "PUT", url, body, options});
}
patch(url, body, options) {
return this.send({method: "PATCH", url, body, options});
}
}
Feq.fetch = fetch;