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