forked from smartface/sf-extension-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-call.js
389 lines (371 loc) · 14 KB
/
service-call.js
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
* Smartface Service-Call helper module
* @module service-call
* @type {object}
* @author Alper Ozisik <alper.ozisik@smartface.io>
* @copyright Smartface 2018
*/
"use strict";
const Http = require("sf-core/net/http");
const httpMap = new WeakMap();
const optionsMap = new WeakMap();
const mixinDeep = require('mixin-deep');
const copy = require("./copy");
const METHODS_WITHOUT_BODY = ["GET", "HEAD"];
const BASE_HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json",
"Accept-Language": global.Device.language,
"Cache-Control": "no-cache"
};
Object.freeze(BASE_HEADERS);
const queryString = require('query-string');
const reHTTPUrl = /^http(s?):\/\//i;
const { createAsyncGetter } = require("./async");
const getHttp = createAsyncGetter(() => new Http());
const reParseBodyAsText = /(?:application\/(?:x-csh|json|javascript|rtf|xml)|text\/.*|.*\/.*(:?\+xml|xml\+).*)/i;
const reJSON = /^application\/json/i;
/**
* Helper class for calling JSON based restful services.
* @public
* @example
* //shared service-call.js file
* const ServiceCall = require("sf-extension-utils/lib/service-call");
* const sc = new ServiceCall({
* baseUrl: "http://api.myBaseUrl.com",
* logEnabled: true,
* headers: {
* apiVersion: "1.0"
* }
* });
* module.exports = exports = sc;
*
*
* // services/user.js
* const sc = require("./serviceConfig");
*
* Object.assign(exports, {
* login
* });
*
* function login(userName, password) {
* return new Promise((resolve, reject) => {
* sc.request(`/auth/login?emine=3`, {
* method: "POST",
* body: {
* userName,
* password
* }
* }).then(response => {
* sc.setHeader("Authorization", "Bearer " + response.token);
* resolve(response);
* }).catch(err => {
* reject(err);
* });
* });
* }
*
*
* // pages/pgLogin.js
* const userService = require("../services/user");
*
* page.btnLogin.onPress = () => {
* userService.login(page.tbUserName.text, page.tbPassword.text).then(()=> {
* Rouger.go("pgDashboard");
* }).catch(()=> {
* alert("Cannot login");
* });
* };
*
*/
class ServiceCall {
/**
* Creates a ServiceCall helper class with common configuration to be used across multiple service calls.
* @param {object} options - Cofiguration of service call helper object (required)
* @param {string} options.baseUrl - Base URL of all future service calls (required)
* @param {number} [options.timeout = 60000] - Timeout value for service calls. If not provided it uses the default timeout value from sf-core http
* @param {boolean} [options.logEnabled = false] - Logs the service requests & responses to console
* @param {object} [options.headers] - Sets the default headers for this configuration
* @example
* const ServiceCall = require("sf-extension-utils/lib/service-call");
* const sc = new ServiceCall({
* baseUrl: "http://smartface.io",
* logEnabled: false,
* headers: {
* apiVersion: "1.0"
* }
* })
*/
constructor(options) {
options = copy(options);
options.baseUrl = options.baseUrl || "";
const httpOptions = {};
if (options.timeout)
httpOptions.timeout = options.timeout;
const http = new Http(httpOptions);
httpMap.set(this, http);
optionsMap.set(this, options);
}
/**
* Sets headers for this configuration. Either sets one by each call or sets them in bulk
* @method
* @param {string} key - Header name to set
* @param {string} value - Value to set of the key. If value is not a string, key is removed from header
* @param {object} headers - headers object to set multipe header values at once
* @example
* //After login
* sc.setHeader("Authorization", "Basic 12345");
* @example
* //After logout
* sc.setHeader("Authorization");
* @example
* // set multiple headers at once
* sc.setHeader({
* environment: "test",
* apiVersion: "1.2" //replaces the existing
* });
*/
setHeader(key, value) {
const serviceCallOptions = optionsMap.get(this);
if (typeof key === "object") {
for (let k in key) {
let v = key[k];
this.setHeader(k, v);
}
}
else if (typeof key === "string") {
if (value) {
serviceCallOptions.headers[key] = String(value);
}
else
delete serviceCallOptions.headers[key];
}
else
throw Error("key must be string or object");
}
/**
* Gets a copy of headers used
* @method
* @returns {object} headers
*/
getHeaders() {
const serviceCallOptions = optionsMap.get(this);
return copy(serviceCallOptions.headers);
}
/**
* Base URL for this service-call library uses. This can be get and set
* @property {string} baseUrl
*/
get baseUrl() {
const serviceCallOptions = optionsMap.get(this);
return serviceCallOptions.baseUrl;
}
set baseUrl(value) {
const serviceCallOptions = optionsMap.get(this);
return serviceCallOptions.baseUrl = value;
}
/**
* creates a request options object for http request
* @method
* @param {string} endpointPath - Added to the end of the base url to form the url
* @param {object} options - Request specific options
* @param {string} method - HTTP method of this request
* @param {object} [options.body] - Request payload body. This object will be automatically stringified
* @param {object} [options.q] - Query string string object. Combines with the url
* @param {object} [options.query] - Alias for options.q
* @param {object} [options.headers] - Request specific headers. In conflict with configuration, those values are used
* @param {boolean} [options.logEnabled] - Request specific log option
* @param {string} [options.user] - Basic authentication user. Must be used with options.password
* @param {string} [options.password] - Basic authentication password. Must be used with options.user
* @param {boolean} [options.fullResponse=false] - Resolved promise contains full response including `headers`, `body` and `status`
* @returns {object} http request object
* @example
* var reqOps = sc.createRequestOptions(`/auth/login`, {
* method: "POST",
* body: {
* userName,
* password
* },
* headers: {
* "Content-Type": "application/json"
* }
* });
* ServiceCall.request(reqOps).then((result) => {
* //logic
* }).catch((err) => {
* //logic
* });
*/
createRequestOptions(endpointPath, options) {
const serviceCallOptions = optionsMap.get(this);
if (!serviceCallOptions)
throw Error("This ServiceCall instnace is not configured");
let url = String(serviceCallOptions.baseUrl + endpointPath);
if (!reHTTPUrl.test(url))
throw Error(`URL is not valid for http(s) request: ${url}`);
let requestOptions = mixinDeep({
url,
headers: serviceCallOptions.headers,
logEnabled: !!serviceCallOptions.logEnabled,
}, options || {});
return requestOptions;
}
/**
* Combines serviceCall.createRequestOptions and ServiceCall.request (static)
* @method
* @param {string} endpointPath - Added to the end of the base url to form the url
* @param {object} options - Request specific options
* @param {string} method - HTTP method of this request
* @param {object} [options.body] - Request payload body. This object will be automatically stringified
* @param {object} [options.q] - Query string string object. Combines with the url
* @param {object} [options.query] - Alias for options.q
* @param {object} [options.headers] - Request specific headers. In conflict with configuration, those values are used
* @param {boolean} [options.logEnabled] - Request specific log option
* @param {string} [options.user] - Basic authentication user. Must be used with options.password
* @param {string} [options.password] - Basic authentication password. Must be used with options.user
* @returns {Promise}
* @see ServiceCall.createRequestOptions
* @see ServiceCall.request
* @example
* function login(userName, password) {
* return sc.request("/auth/login", {
* method: "POST",
* body: {
* userName,
* password
* }
* });
* }
*/
request(endpointPath, options) {
const requestOptions = this.createRequestOptions(endpointPath, options);
return ServiceCall.request(requestOptions);
}
/**
* Performs a service call and returns a promise to handle
* @static
* @method
* @param {object} options - Request specific options
* @param {string} options.method - HTTP method of this request
* @param {string} options.url - Full Http url
* @param {object} [options.body] - Request payload body. This object will be automatically stringified
* @param {object} [options.headers] - Full request headers
* @param {boolean} [options.logEnabled] - Request specific log option
* @param {string} [options.user] - Basic authentication user. Must be used with options.password
* @param {string} [options.password] - Basic authentication password. Must be used with options.user
* @param {boolean} [options.fullResponse=false] - Resolved promise contains full response including `headers`, `body` and `status`
* @returns {Promise}
* @example
* var reqOps = sc.createRequestOptions(`/auth/login`, {
* method: "POST",
* body: {
* userName,
* password
* },
* headers: {
* "Content-Type": "application/json"
* }
* });
* ServiceCall.request(reqOps).then((result) => {
* //logic
* }).catch((err) => {
* //logic
* });
*/
static request(options) {
options = Object.assign({}, options);
let { fullResponse = false } = options;
let query = options.q || options.query;
options.url = String(options.url);
if (query) {
let urlParts = options.url.split("?");
let q = Object.assign(queryString.parse(urlParts[1]), query);
let qString = queryString.stringify(q);
urlParts[1] = qString;
options.url = urlParts.join("?");
}
return new Promise((resolve, reject) => {
let requestOptions = mixinDeep({
onLoad: response => {
try {
response.logEnabled = !!options.logEnabled;
bodyParser(response);
if (response.body.success === false)
reject(fullResponse ? response : response.body);
else
resolve(fullResponse ? response : response.body);
}
catch (ex) {
reject(ex);
}
},
onError: e => {
e.headers = e.headers || {};
e.body = e.body || "";
e.logEnabled = !!options.logEnabled;
bodyParser(e);
reject(e);
},
headers: {}
}, options);
if (METHODS_WITHOUT_BODY.indexOf(requestOptions.method) !== -1) {
if (requestOptions.body) {
delete requestOptions.body;
}
if (requestOptions.headers && requestOptions.headers["Content-Type"])
delete requestOptions.headers["Content-Type"];
options.logEnabled && console.log("request", requestOptions);
}
else {
options.logEnabled && console.log("request", requestOptions);
if (requestOptions.body && typeof requestOptions.body === "object" &&
requestOptions.headers["Content-Type"].startsWith("application/json")) {
requestOptions.body = JSON.stringify(requestOptions.body);
}
}
if (options.http) {
options.http.request(requestOptions);
}
else {
getHttp().then(http => http.request(requestOptions));
}
});
}
/**
* Default values of headers
* @static
* @readonly
* @property {object} header object
*/
static get BASE_HEADERS() { return BASE_HEADERS; }
}
function bodyParser(response) {
const contentType = (response.headers && getContentType(response.headers)) || "";
reJSON.lastIndex = reParseBodyAsText.lastIndex = 0;
if (reParseBodyAsText.test(contentType))
response.body = response.body.toString();
if (reJSON.test(contentType)) {
try {
response.body = JSON.parse(response.body);
response.logEnabled && console.log("Response body ", response.body);
}
catch (ex) {
response.logEnabled && console.log("Response is not a JSON\nResponse Body ", response.body);
}
}
if (response.logEnabled && typeof response.body === "string")
console.log("Response body (non-json) ", response.body);
}
const getContentType = (headers = {}) => {
let contentType = headers["Content-Type"];
if (!contentType) {
for (let h in headers) {
if (h.toLowerCase() === "content-type") {
contentType = headers[h];
break;
}
}
}
return contentType;
};
module.exports = exports = ServiceCall;