Yangman - the execution time is not right
[dlux.git] / modules / yangman-resources / src / main / resources / yangman / services / yangman.services.js
1 define([], function () {
2     'use strict';
3
4     angular.module('app.yangman').service('YangmanService', YangmanService);
5
6     YangmanService.$inject = [
7         'RequestBuilderService',
8         'YangUtilsService',
9         'YangUtilsRestangularService',
10         'ENV',
11         'ParsingJsonService',
12         'RequestsService',
13         'PathUtilsService',
14         'constants',
15     ];
16
17     function YangmanService(
18         RequestBuilderService,
19         YangUtilsService,
20         YangUtilsRestangularService,
21         ENV,
22         ParsingJsonService,
23         RequestsService,
24         PathUtilsService,
25         constants
26     ){
27         var service = {
28             cutUrl: cutUrl,
29             checkRpcReceivedData: checkRpcReceivedData,
30             executeRequestOperation: executeRequestOperation,
31             fillNodeFromResponse: fillNodeFromResponse,
32             getDataStoreIndex: getDataStoreIndex,
33             handleNodeIdentifier: handleNodeIdentifier,
34             prepareAllRequestData: prepareAllRequestData,
35             prepareReceivedData: prepareReceivedData,
36             putIntoObj: putIntoObj,
37             setSrcDataByDataType: setSrcDataByDataType,
38             validateFile: validateFile,
39         };
40
41         return service;
42
43         /**
44          * Handle param continuum between header path array and node data
45          * @param parametersList
46          * @param selectedSubApi
47          * @param node
48          */
49         function handleNodeIdentifier(parametersList, selectedSubApi, node){
50             var identifier = RequestsService.findIdentifierByParam(
51                 parametersList, selectedSubApi.pathArray[selectedSubApi.pathArray.length - 1]
52             );
53
54             if ( identifier ){
55                 PathUtilsService.fillListNode(node, identifier.label, identifier.value);
56             }
57         }
58
59         /**
60          * Put data to output container if root node is rpc
61          * @param data
62          * @param node
63          * @returns {*}
64          */
65         function checkRpcReceivedData(data, node){
66             return node.type === constants.NODE_RPC ? cutData(data) : data;
67
68             function cutData(data){
69                 return {
70                     output: data[node.label].output,
71                 };
72             }
73         }
74
75         /**
76          * Put source object into destination object by source properties
77          * @param sourceObj
78          * @param destinationObj
79          */
80         function putIntoObj(sourceObj, destinationObj, containter){
81             if ( sourceObj ) {
82                 Object.keys(sourceObj).forEach(function(prop){
83                     destinationObj[containter] = destinationObj[containter] ? destinationObj[containter] : {};
84                     destinationObj[containter][prop] = sourceObj[prop];
85                 });
86             }
87         }
88
89         /**
90          * Prepare request date before filling into node depends on method and node type
91          * @param node
92          * @param method
93          * @param rData
94          * @param sData
95          * @param outputType
96          * @returns {*}
97          */
98         function prepareReceivedData(node, method, rData, sData, outputType){
99             var prepareType = {
100                 rpc: function (){
101
102                     if ( outputType === constants.DISPLAY_TYPE_FORM ){
103                         var dObj = {};
104
105                         if ( !sData ) {
106                             sData = {};
107                             sData[node.label] = {};
108                         }
109
110                         putIntoObj(rData, dObj, node.label);
111                         putIntoObj(sData[node.label] ? sData[node.label] : sData, dObj, node.label);
112                         return dObj;
113                     } else {
114                         return rData;
115                     }
116                 },
117                 default: function (){
118                     var methodType = {
119                         GET: function () {
120                             if ( node ){
121                                 node.clear();
122                             }
123                             return rData;
124                         },
125                         DELETE: function () {
126                             if ( node ) {
127                                 node.clear();
128                             }
129                             return {};
130                         },
131                         DEFAULT: function () {
132                             return rData;
133                         },
134                     };
135
136                     return (methodType[method] || methodType.DEFAULT)();
137                 },
138             };
139
140             return (prepareType[node ? node.type : 'default'] || prepareType.default)();
141         }
142
143         /**
144          * Validating collection import file
145          * @param data
146          * @param checkArray
147          * @returns {*}
148          */
149         function validateFile(data, checkArray){
150             try {
151                 var obj = ParsingJsonService.parseJson(data);
152
153                 return obj && obj.every(function (el){
154                     return checkArray.every(function (arr){
155                         return el.hasOwnProperty(arr);
156                     });
157                 });
158             } catch (e) {
159                 return e;
160             }
161         }
162
163         /**
164          * Return index of selected datastore in list
165          * @param list
166          * @param dataStore
167          * @returns {*}
168          */
169         function getDataStoreIndex(list, dataStore){
170             var rIndex = null,
171                 result = list.some(function (item, index) {
172                     rIndex = index;
173                     return item.label === dataStore;
174                 });
175
176             return result ? rIndex : null;
177         }
178
179         /**
180          * Apply all parametrized values into request (data, url, pathArray)
181          * @param allPreparedData
182          * @param params
183          * @param selSubApiCopy
184          * @param requestUrl
185          */
186         function setParametrizedData(allPreparedData, params, selSubApiCopy, requestUrl){
187             allPreparedData.reqFullUrl = RequestsService.applyParamsToStr(params, requestUrl);
188
189             // apply parametrized value into request data in string form
190             allPreparedData.reqString =
191                 selSubApiCopy ? RequestsService.applyParamsToStr(params, selSubApiCopy.buildApiRequestString()) : '';
192
193             if ( !angular.equals(allPreparedData.reqFullUrl, requestUrl) && selSubApiCopy ){
194                 // fill parametrized data into path array
195                 PathUtilsService.fillPath(selSubApiCopy.pathArray, allPreparedData.reqFullUrl);
196             }
197
198             allPreparedData.reqData = RequestsService.applyParamsToObj(params, allPreparedData.srcData);
199         }
200
201         /**
202          * Set source data into request object based on shown data type
203          * @param allPreparedData
204          * @param node
205          * @param requestData
206          * @param dataType
207          */
208         function setSrcDataByDataType(allPreparedData, node, requestData, dataType){
209             if ( dataType === constants.DISPLAY_TYPE_FORM && node){
210                 node.buildRequest(RequestBuilderService, requestData, node.module);
211                 allPreparedData.srcData = angular.copy(requestData);
212             }
213             else {
214                 allPreparedData.srcData = requestData;
215             }
216         }
217
218         /**
219          * Prepare all necessary data for executing or saving request
220          * @param selectedApi
221          * @param selectedSubApi
222          * @param operation
223          * @param node
224          * @param dataType
225          * @param requestUrl
226          * @param requestData
227          * @param params
228          * @returns {{customRestangular: null, headers: {}, operation: string, reqString: string, reqHeaders: {},
229          *          reqData: {}}}
230          */
231         function prepareAllRequestData(selectedApi, selectedSubApi, operation, node, dataType, requestUrl, requestData,
232                                        params) {
233             var allPreparedData = {
234                     customRestangular: null,
235                     headers: {},
236                     operation: '',
237                     reqString: '',
238                     reqHeaders: {},
239                     reqData: '',
240                     srcData: '',
241                     reqFullUrl: '',
242                 },
243                 selSubApiCopy = angular.copy(selectedSubApi);
244
245             setSrcDataByDataType(allPreparedData, node, requestData, dataType);
246             setParametrizedData(allPreparedData, params, selSubApiCopy, requestUrl);
247
248             // prepare req data
249             if (operation === constants.OPERATION_GET || operation === constants.OPERATION_DELETE){
250                 allPreparedData.srcData = null;
251                 allPreparedData.reqData = null;
252             }
253             else if ( operation === constants.OPERATION_POST ){
254
255                 if ( selSubApiCopy ) {
256                     allPreparedData.reqData = YangUtilsService.postRequestData(
257                         allPreparedData.reqData,
258                         allPreparedData.reqString,
259                         selSubApiCopy
260                     );
261                 }
262             }
263
264             // set correct host into restangular based on shown data type and prepare data
265             if ( dataType === constants.DISPLAY_TYPE_REQ_DATA ){
266                 var parser = locationHelper(allPreparedData.reqFullUrl, ['pathname', 'origin']),
267                     raParam = '';
268
269                 YangUtilsRestangularService.setBaseUrl(parser.origin);
270                 allPreparedData.reqString = parser.pathname.slice(1).split('/');
271                 raParam = allPreparedData.reqString.shift();
272                 allPreparedData.reqString = allPreparedData.reqString.join('/');
273
274                 allPreparedData.customRestangular = YangUtilsRestangularService.one(raParam);
275
276             } else {
277
278                 YangUtilsRestangularService.setBaseUrl(ENV.getBaseURL('MD_SAL'));
279                 allPreparedData.customRestangular  = YangUtilsRestangularService.one('restconf');
280
281                 if ( node ) {
282                     allPreparedData.headers = YangUtilsService.prepareHeaders(allPreparedData.reqData);
283                 }
284             }
285
286             allPreparedData.operation = YangUtilsService.prepareOperation(operation);
287             return allPreparedData;
288         }
289
290         function cutUrl(url){
291             return url.indexOf('restconf') > -1 ? url.split('restconf')[1].substring(1) : url;
292         }
293
294         /**
295          * Execute request built from this data
296          * @param selectedApi
297          * @param selectedSubApi
298          * @param operation
299          * @param node
300          * @param dataType
301          * @param requestUrl
302          * @param requestData
303          * @param successCbk
304          * @param errorCbk
305          * @param params
306          */
307         function executeRequestOperation(selectedApi, selectedSubApi, operation, node, dataType, requestUrl,
308                                          requestData, params, successCbk, errorCbk) {
309
310             YangUtilsRestangularService.setFullResponse(true);
311
312             // prepare all necessary data
313             var allPreparedData = prepareAllRequestData(selectedApi, selectedSubApi, operation, node, dataType,
314                 requestUrl, requestData, params);
315
316             // executing operation
317             allPreparedData.customRestangular.customOperation(
318                 allPreparedData.operation.toLowerCase(),
319                 allPreparedData.reqString,
320                 null,
321                 allPreparedData.headers,
322                 allPreparedData.reqData
323             )
324             .then(
325                 function (response) {
326                     (successCbk || angular.noop)(finishExecuting(response), response);
327                 },
328                 function (response) {
329                     (errorCbk || angular.noop)(finishExecuting(response), response);
330                 }
331             );
332
333             function finishExecuting(response){
334
335                 return {
336                     status: response.status,
337                     statusText: response.statusText,
338                     time: null,
339                     requestData: allPreparedData.reqData,
340                     requestSrcData: allPreparedData.srcData,
341                 };
342             }
343         }
344
345         /**
346          * Method for parsing path to additional properties based on JS LOCATION
347          * @param path
348          * @param properties
349          * @returns {{}}
350          */
351         function locationHelper(path, properties){
352             var parser = document.createElement('a'),
353                 obj = {};
354
355             parser.href = path;
356
357             properties.forEach(function (prop) {
358                 obj[prop] = parser[prop];
359             });
360
361             return obj;
362         }
363
364         /**
365          * Fill node values from response
366          * @param node
367          * @param data
368          */
369         function fillNodeFromResponse(node, data){
370             var props = data ? Object.getOwnPropertyNames(data) : [];
371
372             // fill each property - needed for root mountpoint node,
373             // in other cases there should be only one property anyway
374             props.forEach(function (p) {
375                 node.fill(p, data[p]);
376             });
377         }
378     }
379
380 });