blob: 22ee775080128374e2eb0f3f0a2b25f59fbe839f [file] [log] [blame]
ilanap061ca932019-08-04 10:16:33 +03001/*
2 * Copyright © 2016-2017 European Support Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16const needle = require('needle');
17const fs = require('fs');
18require('node-zip');
19var btoa = require('btoa');
20const md5 = require('md5');
21const _ = require('lodash');
22
23function getOptionsForRequest(context, method, path, type) {
24 if (type == undefined || type == null) {
25 type = context.defaultServerType
26 }
27 let server = context.getUrlForType(type);
28 let options = {
29 method: method,
30 url: server + path,
31 headers: _.clone(context.headers[type])
32 };
33// options.headers["Content-Type"] = "application/json";
34// options.headers["accept"] = "application/json";
35 return options;
36}
37
38function _requestBinaryFormData(context, method, path, fileName, formInputName, type) {
39 let options = getOptionsForRequest(context, method, path, type);
40 let formData = {};
41 if (method === 'POST' || method === 'PUT') {
42 //formData[formInputName] = fs.createReadStream(fileName);
43 //options.formData = formData;
44 let fileData = {
45 file: fileName
46 };
47 fileData['content_type'] = 'multipart/form-data';
48 options.formData = {};
49 options.formData[formInputName] = fileData;
50 }
51 return _request(context, method, path, options);
52}
53function _requestBinaryBody(context, method, path, fileName, type) {
54 let options = getOptionsForRequest(context, method, path, type);
55 if (method === 'POST' || method === 'PUT') {
56 options.body = fs.createReadStream(fileName);
57 options.headers['Content-Type'] = 'application/octet-stream';
58
59 }
60 return _request(context, method, path, options);
61}
62
63
64function _requestPayload(context, method, path, filePath, type) {
65 let options = getOptionsForRequest(context, method, path, type);
66 options.json = _createPayload(filePath);
67 options.headers['Content-MD5'] = addCheckSum(options.json);
68 return _request(context, method, path, options);
69}
70
71function _requestRest(context, method, path, data, type) {
72 let options = getOptionsForRequest(context, method, path, type);
73 if (method === 'POST' || method === 'PUT') {
74 options.json = data;
75 }
76 return _request(context, method, path, options);
77}
78
79function _request(context, method, path, options) {
80 console.log('--> Calling REST ' + options.method +' url: ' + options.url);
81 let inputData = options.json;
82 let needleOptions = {headers: options.headers, rejectUnauthorized: false};
83 if (inputData == undefined) {
84 if (options.formData != undefined) {
85 inputData = options.formData;
86 needleOptions.multipart = true;
87 }
88 if (inputData && inputData.body != undefined) {
89 inputData = options.body;
90 }
91 } else {
92 needleOptions.json = true;
93 }
94 return needle(method, options.url, inputData, needleOptions)
95 .then(function(result) {
96 context.inputData = null;
97 let isExpected = (context.shouldFail) ? (result.statusCode != 200 && result.statusCode != 201) : (result.statusCode == 200 || result.statusCode == 201);
98 data = result.body;
99 if (!isExpected) {
100 console.log('Did not get expected response code');
101 throw 'Status Code was ' + result.statusCode ;
102 }
103 if (context.shouldFail && context.errorCode) {
104 if (typeof data === 'string' && data) {
105 data = JSON.parse(data);
106 }
107 let errorCode = data.errorCode;
108 let contextErrorCode = context.errorCode;
109 context.errorCode = null;
110 if (errorCode !== contextErrorCode) {
111 throw 'Error Code was ' + errorCode + ' instead of ' + contextErrorCode;
112 }
113 }
114 if (context.shouldFail && context.errorMessage) {
115 if (typeof data === 'string' && data) {
116 data = JSON.parse(data);
117 }
118 let errorMessage = data.message;
119 let contextErrorMessage = context.errorMessage;
120 context.errorMessage = null;
121 if (errorMessage !== contextErrorMessage) {
122 throw 'Error Message was ' + errorMessage + ' instead of ' + contextErrorMessage;
123 }
124 }
125 if (context.shouldFail) {
126 context.shouldFail = false;
127 return({statusCode: result.statusCode, data: {}});
128 }
129
130 if (typeof data === 'string' && data) {
131 if (data.startsWith('[') || data.startsWith('{')) {
132 data = JSON.parse(data);
133 }
134 }
135 context.responseData = data;
136 context.inputData = data;
137 return({statusCode: result.statusCode, data: data});
138
139 })
140 .catch(function(err) {
141 console.error('Request URL: ' + options.url);
142 console.error('Request Method: ' + options.method);
143 console.log(err);
144 throw err;
145 })
146}
147
148function download(context, path, filePath, type) {
149 if (type == undefined || type == null) {
150 type = context.defaultServerType
151 }
152 let server = context.getUrlForType(type);
153 let options = {
154 method: 'GET',
155 url: server + path,
156 headers: context.headers[type]
157 };
158
159 console.log('--> Calling REST download url: ' + options.url);
160 return needle('GET', options.url, {}, {
161 headers: options.headers,
162 rejectUnauthorized: false,
163 output: filePath
164 })
165 .then(function (result) {
166 let zipFile = fs.readFileSync(filePath, 'binary');
167 let zip = new JSZip(zipFile, {base64: false, checkCRC32: true});
168 if (zip.files['MANIFEST.json']) {
169 let manifestData = zip.files['MANIFEST.json']._data;
170 manifestData = manifestData.replace(/\\n/g, '');
171 context.responseData = JSON.parse(manifestData);
172 }
173 return zip;
174 })
175 .catch(function (err) {
176 console.error('Request URL: ' + options.url);
177 console.error('Request Method: ' + options.method);
178 throw err;
179 })
180}
181
182function _random() {
183 let d = new Date();
184 return d.getTime().toString().split('').reverse().join('');
185}
186
187function _getJSONFromFile(file) {
188 return JSON.parse(fs.readFileSync(file, 'utf8'));
189}
190
191function _createPayload(fileName) {
192 var body = fs.readFileSync(fileName);
193 let payload = {
194 payloadData: body.toString('base64'),
195 payloadName: fileName.substring(fileName.lastIndexOf("/") + 1 )
196 };
197 return payload;
198}
199
200function addCheckSum(payloadData) {
201 let _md5 = md5(JSON.stringify(payloadData));
202 return btoa(_md5.toLowerCase());
203}
204
205function _getFile(file, format) {
206 if(format === '' ){
207 return fs.readFileSync(file)
208 }
209 return fs.readFileSync(file, format);
210}
211
212
213module.exports = {
214 getFile: _getFile,
215 request: _requestRest,
216 requestPayload: _requestPayload,
217 requestBinaryFormData: _requestBinaryFormData,
218 requestBinaryBody: _requestBinaryBody,
219 random : _random,
220 getJSONFromFile: _getJSONFromFile,
221 download: download,
222 payload: _createPayload
223};