1
|
|
|
"use strict"; |
2
|
|
|
|
3
|
2 |
|
const requestPromise = require('request-promise-native'); |
4
|
2 |
|
const pkg = require('../../package.json'); |
5
|
2 |
|
const logger = require('../logger/taskLogger')('Client'); |
6
|
2 |
|
const Response = require('../model/Response'); |
7
|
|
|
|
8
|
2 |
|
const defaultOptionList = { |
9
|
|
|
headers: {'User-Agent': pkg.name}, |
10
|
|
|
json: true, |
11
|
|
|
simple: false, |
12
|
|
|
resolveWithFullResponse: true |
13
|
|
|
}; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param {Request} request |
17
|
|
|
* |
18
|
|
|
* @returns {Promise<Response|Error>} |
19
|
|
|
*/ |
20
|
2 |
|
module.exports = (request) => { |
21
|
|
|
|
22
|
|
|
const optionList = Object.assign( |
23
|
|
|
{}, |
24
|
|
|
defaultOptionList, |
25
|
|
|
{ |
26
|
|
|
uri: request.getUri(), |
27
|
|
|
method: request.getMethod(), |
28
|
|
|
headers: Object.assign({}, defaultOptionList.headers, request.getHeaders()), |
29
|
|
|
json: request.isJson() |
30
|
|
|
} |
31
|
|
|
); |
32
|
|
|
|
33
|
7 |
|
if (request.getForm() && Object.keys(request.getForm()).length > 0) { |
34
|
1 |
|
optionList.form = request.getForm(); |
35
|
|
|
} |
36
|
7 |
|
if (request.getPayload() && Object.keys(request.getPayload()).length > 0) { |
37
|
1 |
|
optionList.body = request.getPayload(); |
38
|
|
|
} else { |
39
|
6 |
|
optionList.body = optionList.json === true ? {} : ''; |
40
|
|
|
} |
41
|
7 |
|
if (request.getQueryString() && Object.keys(request.getQueryString()).length > 0) { |
42
|
1 |
|
optionList.qs = request.getQueryString(); |
43
|
|
|
} else { |
44
|
6 |
|
optionList.qs = optionList.json === true ? {} : null; |
45
|
|
|
} |
46
|
|
|
|
47
|
7 |
|
const transformResponseToResponseObject = response => { |
48
|
|
|
return new Response( |
49
|
|
|
response.body, |
50
|
|
|
response.statusCode, |
51
|
|
|
response.headers, |
52
|
|
|
request |
53
|
|
|
); |
54
|
|
|
}; |
55
|
|
|
|
56
|
7 |
|
const transformErrorToResponseObject = error => { |
57
|
|
|
logger.debug('[Error] Conversion to Response.', {options: optionList}); |
58
|
|
|
|
59
|
2 |
|
return Promise.resolve(new Response( |
60
|
|
|
optionList.json === true ? { |
61
|
|
|
error: error.error.code, |
62
|
|
|
message: error.message |
63
|
|
|
} : `${error.error.code} ${error.message}`, |
64
|
|
|
500, |
65
|
|
|
{}, |
66
|
|
|
request |
67
|
|
|
)); |
68
|
|
|
}; |
69
|
|
|
|
70
|
7 |
|
const logResponseObject = response => { |
71
|
|
|
logger.debug('[Reponse]', {response: response, options: optionList}); |
72
|
|
|
|
73
|
7 |
|
return response; |
74
|
|
|
}; |
75
|
|
|
|
76
|
7 |
|
logger.debug('[Request]', {options: optionList}); |
77
|
|
|
|
78
|
7 |
|
const transform = requestPromise(optionList) |
79
|
|
|
.then(transformResponseToResponseObject, transformErrorToResponseObject); |
80
|
|
|
|
81
|
7 |
|
return transform |
82
|
|
|
.then(logResponseObject); |
83
|
|
|
}; |
84
|
|
|
|