-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathParent.ts
More file actions
74 lines (63 loc) · 2.36 KB
/
Copy pathParent.ts
File metadata and controls
74 lines (63 loc) · 2.36 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
import { Injectable, Inject } from '@angular/core';
import { Headers, Http } from '@angular/http';
// Need to import interfaces dependencies
// Bug TypeScript https://github.com/Microsoft/TypeScript/issues/5938
import { Observable } from 'rxjs/Observable';
import { RequestOptionsArgs } from '@angular/http/src/interfaces';
import { Response } from '@angular/http/src/static_response';
import { WpApiLoader } from './Loaders';
import { stripTrailingSlash } from './utils';
import { AuthSession } from './AuthSession';
import { IParent } from './interfaces';
@Injectable()
export class WpApiParent implements IParent {
constructor(
public wpApiLoader: WpApiLoader,
public http: Http
) { }
protected getToken(): string {
let sessionCredentials = AuthSession.getSession();
return sessionCredentials ? sessionCredentials.token : null;
}
protected hasToken(): boolean {
return this.getToken() ? true : false;
}
protected getWebServiceUrl(postfix: string): string {
return this.wpApiLoader.getWebServiceUrl(postfix);
}
protected getDefaultOptions(
options: RequestOptionsArgs = { headers: new Headers() }
): RequestOptionsArgs {
if (!options.headers) {
options.headers = new Headers();
}
if (!options.headers.has('Authorization') && this.hasToken()) {
options.headers.append('Authorization', `Bearer ${this.getToken()}`);
}
return options;
}
httpGet(url: string, options = {}) {
options = this.getDefaultOptions(options);
return this.http.get(this.getWebServiceUrl(url), options);
}
httpHead(url: string, options = {}) {
options = this.getDefaultOptions(options);
return this.http.head(this.getWebServiceUrl(url), options);
}
httpDelete(url: string, options = {}) {
options = this.getDefaultOptions(options);
return this.http.delete(this.getWebServiceUrl(url), options);
}
httpPost(url: string, body = {}, options = {}) {
options = this.getDefaultOptions(options);
return this.http.post(this.getWebServiceUrl(url), body, options);
}
httpPut(url: string, body = {}, options = {}) {
options = this.getDefaultOptions(options);
return this.http.put(this.getWebServiceUrl(url), body, options);
}
httpPatch(url: string, body = {}, options = {}) {
options = this.getDefaultOptions(options);
return this.http.patch(this.getWebServiceUrl(url), body, options);
}
}