2 * Copyright © 2016-2017 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 const needle = require('needle');
17 const fs = require('fs');
19 var btoa = require('btoa');
20 const md5 = require('md5');
21 const _ = require('lodash');
23 function getOptionsForRequest(context, method, path, type) {
24 if (type == undefined || type == null) {
25 type = context.defaultServerType
27 let server = context.getUrlForType(type);
31 headers: _.clone(context.headers[type])
33 // options.headers["Content-Type"] = "application/json";
34 // options.headers["accept"] = "application/json";
38 function _requestBinaryFormData(context, method, path, fileName, formInputName, type) {
39 let options = getOptionsForRequest(context, method, path, type);
41 if (method === 'POST' || method === 'PUT') {
42 //formData[formInputName] = fs.createReadStream(fileName);
43 //options.formData = formData;
47 fileData['content_type'] = 'multipart/form-data';
48 options.formData = {};
49 options.formData[formInputName] = fileData;
51 return _request(context, method, path, options);
53 function _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';
60 return _request(context, method, path, options);
64 function _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);
71 function _requestRest(context, method, path, data, type) {
72 let options = getOptionsForRequest(context, method, path, type);
73 if (method === 'POST' || method === 'PUT') {
76 return _request(context, method, path, options);
79 function _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;
88 if (inputData && inputData.body != undefined) {
89 inputData = options.body;
92 needleOptions.json = true;
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);
100 console.log('Did not get expected response code');
101 throw 'Status Code was ' + result.statusCode ;
103 if (context.shouldFail && context.errorCode) {
104 if (typeof data === 'string' && data) {
105 data = JSON.parse(data);
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;
114 if (context.shouldFail && context.errorMessage) {
115 if (typeof data === 'string' && data) {
116 data = JSON.parse(data);
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;
125 if (context.shouldFail) {
126 context.shouldFail = false;
127 return({statusCode: result.statusCode, data: {}});
130 if (typeof data === 'string' && data) {
131 if (data.startsWith('[') || data.startsWith('{')) {
132 data = JSON.parse(data);
135 context.responseData = data;
136 context.inputData = data;
137 return({statusCode: result.statusCode, data: data});
140 .catch(function(err) {
141 console.error('Request URL: ' + options.url);
142 console.error('Request Method: ' + options.method);
148 function download(context, path, filePath, type) {
149 if (type == undefined || type == null) {
150 type = context.defaultServerType
152 let server = context.getUrlForType(type);
156 headers: context.headers[type]
159 console.log('--> Calling REST download url: ' + options.url);
160 return needle('GET', options.url, {}, {
161 headers: options.headers,
162 rejectUnauthorized: false,
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);
175 .catch(function (err) {
176 console.error('Request URL: ' + options.url);
177 console.error('Request Method: ' + options.method);
184 return d.getTime().toString().split('').reverse().join('');
187 function _getJSONFromFile(file) {
188 return JSON.parse(fs.readFileSync(file, 'utf8'));
191 function _createPayload(fileName) {
192 var body = fs.readFileSync(fileName);
194 payloadData: body.toString('base64'),
195 payloadName: fileName.substring(fileName.lastIndexOf("/") + 1 )
200 function addCheckSum(payloadData) {
201 let _md5 = md5(JSON.stringify(payloadData));
202 return btoa(_md5.toLowerCase());
205 function _getFile(file, format) {
207 return fs.readFileSync(file)
209 return fs.readFileSync(file, format);
215 request: _requestRest,
216 requestPayload: _requestPayload,
217 requestBinaryFormData: _requestBinaryFormData,
218 requestBinaryBody: _requestBinaryBody,
220 getJSONFromFile: _getJSONFromFile,
222 payload: _createPayload