/
HttpClient.mustache
89 lines (72 loc) · 3 KB
/
HttpClient.mustache
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
87
88
89
import IHttpClient from './IHttpClient';
{{^useRxJS6}}
import { Observable } from 'rxjs/Observable';
{{/useRxJS6}}
{{#useRxJS6}}
import { Observable, from } from 'rxjs';
{{/useRxJS6}}
import 'whatwg-fetch';
import HttpResponse from './HttpResponse';
import {injectable} from 'inversify';
import { Headers } from './Headers';
@injectable()
class HttpClient implements IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse> {
return this.performNetworkCall(url, 'GET', undefined, headers);
}
post(url: string, body?: {}|FormData, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, 'POST', this.getJsonBody(body), this.addJsonHeaders(headers));
}
put(url: string, body?: {}, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, 'PUT', this.getJsonBody(body), this.addJsonHeaders(headers));
}
patch(url: string, body?: {}, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, 'PATCH', this.getJsonBody(body), this.addJsonHeaders(headers));
}
delete(url: string, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, 'DELETE', undefined, headers);
}
private getJsonBody(body?: {}|FormData) {
if (body === undefined || body instanceof FormData) {
return body;
}
return JSON.stringify(body);
}
private addJsonHeaders(headers?: Headers) {
return Object.assign({}, {
'Accept': 'application/json',
'Content-Type': 'application/json'
}, headers);
};
private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable<HttpResponse> {
// when using fetch & a multipart upload, the requests content-type is handled by the browser, so should be left unset otherwise the multipart boundary is not added
if(headers && headers['Content-Type'] === 'multipart/form-data') {
delete headers['Content-Type'];
}
let promise = window.fetch(url, {
method: method,
body: body,
headers: <any>headers
}).then(response => {
let headers: Headers = {};
response.headers.forEach((value, name) => {
headers[name.toString().toLowerCase()] = value;
});
return response.text().then(text => {
let contentType = headers['content-type'] || '';
let payload = contentType.match('application/json') ? JSON.parse(text) : text;
let httpResponse = new HttpResponse(payload, response.status, headers);
if (response.status >= 400)
throw httpResponse;
return httpResponse;
});
});
{{^useRxJS6}}
return Observable.fromPromise(promise);
{{/useRxJS6}}
{{#useRxJS6}}
return from(promise);
{{/useRxJS6}}
}
}
export default HttpClient