/
api.ts
executable file
·77 lines (65 loc) · 1.97 KB
/
api.ts
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
import {
inject,
} from 'aurelia-framework';
import {
HttpClient
} from 'aurelia-fetch-client';
import {
EventAggregator
} from 'aurelia-event-aggregator';
import 'whatwg-fetch';
@inject(HttpClient, EventAggregator)
export class Api {
/**
* Set this property in children class when using this class as inheritance
*/
public baseUrl: string = '';
constructor(public http: HttpClient, public eventAggregator: EventAggregator) {
this.configure();
}
configure() {
this.http.configure((config) => {
config
//.useStandardConfiguration()
.withDefaults({
credentials: 'same-origin'
})
.withBaseUrl(this.baseUrl);
});
}
defaultOptions(options: any = {}) {
let o: any = {
method: 'get',
headers: {}
};
o.headers['Content-Type'] = 'application/json';
return Object.assign({}, o, options);
}
get(entrypoint: string, options: any = {}): Promise < any > {
return this.http.fetch(entrypoint, this.defaultOptions(options));
}
post(entrypoint: string, body: any = {}, options: any = {}): Promise < any > {
let o = this.defaultOptions(options);
o.method = 'post';
o.body = this.normalizeBody(body, options);
return this.http.fetch(entrypoint, o);
}
put(entrypoint: string, body: any = {}, options: any = {}): Promise < any > {
let o = this.defaultOptions(options);
o.method = 'put';
o.body = this.normalizeBody(body, options);
return this.http.fetch(entrypoint, o);
}
delete(entrypoint: string, body: any = {}, options: any = {}): Promise < any > {
let o = this.defaultOptions(options);
o.method = 'delete';
o.body = this.normalizeBody(body, options);
return this.http.fetch(entrypoint, o);
}
normalizeBody(body: any, options: any) {
if (!options.bodyFormat || options.bodyFormat === 'json') {
body = JSON.stringify(body);
}
return body;
}
}