-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest.service.ts
More file actions
executable file
·161 lines (152 loc) · 4.46 KB
/
request.service.ts
File metadata and controls
executable file
·161 lines (152 loc) · 4.46 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import { Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';
import { CacheService } from '../../shared/cache/cache.service';
// Definition configure for API request
// This ONLY definition of class, any changed of value will no effect.
// Please configuring on `configs/config.ts`.
export class RequestServiceConfig {
appKey = '';
prefixUrl = 'http://local.practera.com/'
}
@Injectable()
export class RequestService {
private appkey: string;
private prefixUrl: string;
private apikey: string;
private timelineID: number;
constructor (
@Optional() config: RequestServiceConfig,
private http: HttpClient,
private cacheService: CacheService
) {
// Inject appKey and prefixUrl when RequestServiceConfig loaded
if (config) {
this.appkey = config.appKey;
this.prefixUrl = config.prefixUrl;
}
}
/**
* Return current prefixUrl
* @param {String} prefixUrl
*/
public getPrefixUrl(){
return this.prefixUrl;
}
/**
* Return current appKey
* @param {String} appKey
*/
public getAppkey(){
return this.appkey;
}
/**
* Error handle for API response
* @param {Error} error
*/
private handleError(error) {
let errorFrom = {
api: 'SERVER_ERROR',
},
currentError: any = error;
if (typeof error !== 'object') {
throw 'Unable to process API respond!';
}
if (error.status === 0) { // client unrecoverable error encountered
currentError.frontendCode = errorFrom.api;
} else {
let errorBody = error.body;
currentError.frontendCode = errorBody.data || errorBody.error;
}
return Observable.throw(currentError);
}
// Inject required fields to header of API request
appendHeader(custom: object = {}): HttpHeaders {
// Define default header
custom = _.merge({
'content-type': 'application/json'
}, custom);
let header: HttpHeaders = new HttpHeaders();
_.forEach(custom, (value, key) => {
header = header.set(key, _.toString(value));
});
// Inject apiKey from cached
let apiKey = this.cacheService.getLocal('apikey');
if (!_.isEmpty(apiKey)) {
header = header.set('apikey', _.toString(apiKey));
}
// Inject timelineID from cached
let timelineId = this.cacheService.getLocal('timelineID');
if (timelineId) {
header = header.set('timelineID', _.toString(timelineId));
}
return header;
}
// Set API request options
setOptions(options?): {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
withCredentials?: boolean;
search?: string;
} {
let headers = this.appendHeader();
// setup http params
let params = (options && options.params) ? options.params : new HttpParams();
if (options && options.search) {
_.each(options.search, (value, key) => {
params = params.set(key, _.toString(value));
});
}
let timelineId = this.cacheService.getLocal('timelineID');
if (timelineId) {
params = params.set('timelineID', timelineId);
}
return { headers, params };
}
/**
* Send GET request to server
* @param {String} endPoint
* @param {Object} options
*/
get(endPoint: string = '', options?: any) {
let searchQuery = (options && options.search) ? options.search : null;
options = this.setOptions(options);
options.observe = 'body';
options.responseType = 'json';
options.search = searchQuery;
return this.http.get(this.prefixUrl + endPoint, options)
.map(this.extractData)
.catch(this.handleError);
}
/**
* Send POST request to server
* @param {String} endPoint
* @param {Object} data
* @param {Object} header
*/
post(endPoint: string, data: any, header?: any) {
let headers = this.appendHeader(header);
return this.http.post(this.prefixUrl + endPoint, data, { headers })
.map(this.extractData)
.catch(this.handleError);
}
/**
* Send DELETE request to server
* @param {String} endPoint
* @param {Object} header
*/
delete(endPoint: string, header?:Object) {
return this.http.delete(this.prefixUrl + endPoint, {
headers: this.appendHeader(header)
})
.map(this.extractData)
.catch(this.handleError);
}
// Extract response data and convert it to JSON
extractData(res) {
return res.data || res;
}
}