CSIT Fix for SDC-2585
[sdc.git] / catalog-ui / src / app / ng2 / services / http.service.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import {Injectable, Inject} from '@angular/core';
22 import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
23 import {Observable} from 'rxjs/Observable';
24 import {UUID} from 'angular2-uuid';
25 import 'rxjs/add/operator/map';
26 import 'rxjs/add/operator/catch';
27 import 'rxjs/add/observable/throw';
28 import {Dictionary} from "../../utils/dictionary/dictionary";
29 import {SharingService, CookieService} from "app/services";
30 import { ModalService } from "app/ng2/services/modal.service";
31 import { ServerErrorResponse } from "app/models";
32 import {ErrorMessageComponent} from "../components/ui/modal/error-message/error-message.component";
33 import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config";
34
35 @Injectable()
36 export class HttpService extends Http {
37
38     constructor(backend: XHRBackend, options: RequestOptions, private sharingService: SharingService, private cookieService: CookieService, private modalService: ModalService, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) {
39         super(backend, options);
40         this._defaultOptions.withCredentials = true;
41         this._defaultOptions.headers.append(cookieService.getUserIdSuffix(), cookieService.getUserId());
42     }
43
44     request(request:string|Request, options?:RequestOptionsArgs):Observable<Response> {
45         /**
46          * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
47          * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
48          */
49         if (typeof request === 'string') { // meaning we have to add the token to the options, not in url
50             if (!options) {
51                 // make option object
52                 options = {headers: new Headers()};
53             }
54
55             var uuidValue = this.getUuidValue(request);
56             if(uuidValue!= ''){
57                 options.headers['X-ECOMP-ServiceID'] = uuidValue;
58
59             }
60             options.headers.set('X-ECOMP-RequestID', UUID.UUID());
61
62         } else {
63             // we have to add the token to the url object
64             var uuidValue = this.getUuidValue((<Request>request).url);
65             if(uuidValue!= ''){
66                  request.headers.set('X-ECOMP-ServiceID',uuidValue);
67
68             }
69             request.headers.set('X-ECOMP-RequestID', UUID.UUID());
70         }
71         return super.request(request, options).catch((err) => this.catchError(err));
72     }
73
74     private getUuidValue = (url: string) :string => {
75         let map:Dictionary<string, string> = this.sharingService.getUuidMap();
76         if (map && url.indexOf(this.sdcConfig.api.root) > 0) {
77             map.forEach((key:string) => {
78                 if (url.indexOf(key) !== -1) {
79                     return this.sharingService.getUuidValue(key);
80                 }
81             });
82         }
83         return '';
84     }
85
86     private catchError = (response: Response): Observable<any> => {
87         
88         let modalInstance = this.modalService.createErrorModal("OK");
89         let errorResponse: ServerErrorResponse = new ServerErrorResponse(response);
90         this.modalService.addDynamicContentToModal(modalInstance, ErrorMessageComponent, errorResponse);
91         modalInstance.instance.open();
92         
93         return Observable.throw(response);
94     };
95
96     public static replaceUrlParams(url:string, urlParams:{[index:string]:any}):string {
97         return url.replace(/:(\w+)/g, (m, p1):string => urlParams[p1] || '');
98     }
99
100 }