Yangman - clear indetifiers, fix boolean type, fix history req sent data
[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
14     ];
15
16     function YangmanService(
17         RequestBuilderService,
18         YangUtilsService,
19         YangUtilsRestangularService,
20         ENV,
21         ParsingJsonService,
22         RequestsService
23     ){
24         var service = {
25             checkRpcReceivedData: checkRpcReceivedData,
26             executeRequestOperation: executeRequestOperation,
27             fillNodeFromResponse: fillNodeFromResponse,
28             getDataStoreIndex: getDataStoreIndex,
29             prepareAllRequestData: prepareAllRequestData,
30             prepareReceivedData: prepareReceivedData,
31             validateFile: validateFile,
32         };
33
34         return service;
35
36         function checkRpcReceivedData(data, node){
37             return node.type === 'rpc' ? cutData(data) : data;
38
39             function cutData(data){
40                 return {
41                     output: data[node.label].output,
42                 };
43             }
44         }
45
46         /**
47          * Prepare request date before filling into node depends on method and node type
48          * @param node
49          * @param method
50          * @param rData
51          * @param sData
52          * @param outputType
53          * @returns {*}
54          */
55         function prepareReceivedData(node, method, rData, sData, outputType){
56             var prepareType = {
57                 rpc: function(){
58
59                     if ( outputType === 'form' ){
60                         var dObj = {};
61                         putIntoObj(rData, dObj, node.label);
62                         putIntoObj(sData[node.label] ? sData[node.label] : sData, dObj, node.label);
63                         return dObj;
64                     } else {
65                         return rData;
66                     }
67
68                     /**
69                      * Put source object into destination object by source properties
70                      * @param sourceObj
71                      * @param destinationObj
72                      */
73                     function putIntoObj(sourceObj, destinationObj, containter){
74                         Object.keys(sourceObj).forEach(function(prop){
75                             destinationObj[containter] = destinationObj[containter] ? destinationObj[containter] : {};
76                             destinationObj[containter][prop] = sourceObj[prop];
77                         });
78                     }
79                 },
80                 default: function (){
81                     var methodType = {
82                         GET: function () {
83                             if ( node ){
84                                 node.clear();
85                             }
86                             return rData;
87                         },
88                         DELETE: function () {
89                             if ( node ) {
90                                 node.clear();
91                             }
92                             return {};
93                         },
94                         PUT: function () {
95                             return rData;
96                         },
97                         DEFAULT: function () {
98                             return outputType === 'form' ? sData : rData;
99                         }
100                     };
101
102                     return (methodType[method] || methodType.DEFAULT)();
103                 }
104             };
105
106             return (prepareType[node ? node.type : 'default'] || prepareType.default)();
107         }
108
109         /**
110          * Validating collection import file
111          * @param data
112          * @param checkArray
113          * @returns {*}
114          */
115         function validateFile(data, checkArray){
116             try {
117                 var obj = ParsingJsonService.parseJson(data);
118
119                 return obj && obj.every(function (el){
120                     return checkArray.every(function (arr){
121                         return el.hasOwnProperty(arr);
122                     });
123                 });
124             } catch (e) {
125                 return e;
126             }
127         }
128
129         /**
130          * Return index of selected datastore in list
131          * @param list
132          * @param dataStore
133          * @returns {*}
134          */
135         function getDataStoreIndex(list, dataStore){
136             var rIndex = null,
137                 result = list.some(function (item, index) {
138                     rIndex = index;
139                     return item.label === dataStore;
140                 });
141
142             return result ? rIndex : null;
143         }
144
145         /**
146          * Prepare all necessary data for executing or saving request
147          * @param selectedApi
148          * @param selectedSubApi
149          * @param operation
150          * @param node
151          * @param dataType
152          * @param requestUrl
153          * @param requestData
154          * @param params
155          * @returns {{customRestangular: null, headers: {}, operation: string, reqString: string, reqHeaders: {},
156          *          reqData: {}}}
157          */
158         function prepareAllRequestData(selectedApi, selectedSubApi, operation, node, dataType, requestUrl, requestData,
159                                        params) {
160             var allPreparedData = {
161                 customRestangular: null,
162                 headers: {},
163                 operation: '',
164                 reqString: selectedSubApi ? selectedSubApi.buildApiRequestString() : '',
165                 reqHeaders: {},
166                 reqData: '',
167                 srcData: '',
168             };
169
170             if ( dataType === 'form' && node){
171                 node.buildRequest(RequestBuilderService, requestData, node.module);
172                 allPreparedData.srcData = angular.copy(requestData);
173             }
174             else {
175                 allPreparedData.srcData = requestData;
176             }
177
178             allPreparedData.reqData = RequestsService.applyParams(params, allPreparedData.srcData);
179
180             // prepare req data
181             if (operation === 'GET' || operation === 'DELETE'){
182                 allPreparedData.srcData = null;
183                 allPreparedData.reqData = null;
184             }
185             else if (operation === 'POST'){
186                 allPreparedData.reqData = YangUtilsService.postRequestData(
187                     allPreparedData.reqData,
188                     allPreparedData.reqString,
189                     selectedSubApi
190                 );
191             }
192
193             // set correct host into restangular based on shown data type and prepare data
194             if ( dataType === 'req-data' ){
195                 var parser = locationHelper(requestUrl, ['pathname', 'origin']),
196                     raParam = '';
197
198                 YangUtilsRestangularService.setBaseUrl(parser.origin);
199                 allPreparedData.reqString = parser.pathname.slice(1).split('/');
200                 raParam = allPreparedData.reqString.shift();
201                 allPreparedData.reqString = allPreparedData.reqString.join('/');
202
203                 allPreparedData.customRestangular = YangUtilsRestangularService.one(raParam);
204
205             } else {
206
207                 YangUtilsRestangularService.setBaseUrl(ENV.getBaseURL('MD_SAL'));
208                 allPreparedData.customRestangular  = YangUtilsRestangularService.one('restconf');
209
210                 if ( node ) {
211                     allPreparedData.headers = YangUtilsService.prepareHeaders(allPreparedData.reqData);
212                 }
213             }
214
215             allPreparedData.operation = YangUtilsService.prepareOperation(operation);
216             return allPreparedData;
217         }
218
219         /**
220          * Execute request built from this data
221          * @param selectedApi
222          * @param selectedSubApi
223          * @param operation
224          * @param node
225          * @param dataType
226          * @param requestUrl
227          * @param requestData
228          * @param successCbk
229          * @param errorCbk
230          * @param params
231          */
232         function executeRequestOperation(selectedApi, selectedSubApi, operation, node, dataType, requestUrl,
233                                          requestData, params, successCbk, errorCbk) {
234             var time = {
235                 started: 0,
236                 finished: 0,
237             };
238
239             YangUtilsRestangularService.setFullResponse(true);
240
241             // prepare all necessary data
242             var allPreparedData = prepareAllRequestData(selectedApi, selectedSubApi, operation, node, dataType,
243                 requestUrl, requestData, params);
244
245             // start track time response
246             time.started = new Date().getMilliseconds();
247
248             // executing operation
249             allPreparedData.customRestangular.customOperation(
250                 allPreparedData.operation.toLowerCase(),
251                 allPreparedData.reqString,
252                 null,
253                 allPreparedData.headers,
254                 allPreparedData.reqData
255             )
256             .then(
257                 function (response) {
258                     (successCbk || angular.noop)(finishExecuting(response), response);
259                 },
260                 function (response) {
261                     (errorCbk || angular.noop)(finishExecuting(response), response);
262                 }
263             );
264
265             function finishExecuting(response){
266                 // finish track time response
267                 time.finished = new Date().getMilliseconds();
268                 var spentRequestTime = time.finished - time.started;
269
270                 return {
271                     status: response.status,
272                     statusText: response.statusText,
273                     time: spentRequestTime < 0 ? -(spentRequestTime) : spentRequestTime,
274                     requestData: allPreparedData.reqData,
275                     requestSrcData: allPreparedData.srcData,
276                 };
277             }
278         }
279
280         /**
281          * Method for parsing path to additional properties based on JS LOCATION
282          * @param path
283          * @param properties
284          * @returns {{}}
285          */
286         function locationHelper(path, properties){
287             var parser = document.createElement('a'),
288                 obj = {};
289
290             parser.href = path;
291
292             properties.forEach(function (prop) {
293                 obj[prop] = parser[prop];
294             });
295
296             return obj;
297         }
298
299         /**
300          * Fill node values from response
301          * @param node
302          * @param data
303          */
304         function fillNodeFromResponse(node, data){
305             var props = data ? Object.getOwnPropertyNames(data) : [];
306
307             // fill each property - needed for root mountpoint node,
308             // in other cases there should be only one property anyway
309             props.forEach(function (p) {
310                 node.fill(p, data[p]);
311             });
312         }
313     }
314
315 });