708d91b43c15b5423cd2838cd000bbe54ed183a8
[osm/NG-UI.git] / src / services / RestService.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
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
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
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.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17  */
18
19 /**
20  * @file Provider for REST Service
21  */
22
23 import { HttpClient, HttpHeaders } from '@angular/common/http';
24 import { Injectable } from '@angular/core';
25 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
26 import { TranslateService } from '@ngx-translate/core';
27 import { NotifierService } from 'angular-notifier';
28 import { APIURLHEADER, ERRORDATA } from 'CommonModel';
29 import * as HttpStatus from 'http-status-codes';
30 import { Observable } from 'rxjs';
31 import { isNullOrUndefined } from 'util';
32
33 /**
34  * An Injectable is a class adorned with the @Injectable decorator function.
35  * @Injectable takes a metadata object that tells Angular how to compile and run module code
36  */
37 @Injectable()
38 /** Exporting a class @exports RestService */
39 export class RestService {
40     /** convenient way to modify request made by the http service both before they are sent and after they return */
41     private http: HttpClient;
42     /** API URL. Disabled tslint since server doesn't support https protocol */
43     private apiURL: string = '';
44     /** Notifier service to popup notification @private */
45     private notifierService: NotifierService;
46     /** Instance for active modal service @public */
47     private activeModal: NgbModal;
48     /** insatnce for translate @private */
49     private translateService: TranslateService;
50
51     constructor(http: HttpClient, notifierService: NotifierService, activeModal: NgbModal, translateService: TranslateService) {
52         this.http = http;
53         this.notifierService = notifierService;
54         this.activeModal = activeModal;
55         this.translateService = translateService;
56     }
57
58     /**
59      * Get a resource from the server which identified by a URI.
60      * @param apiURL The URL of the resource to be retrieved.
61      */
62
63     public getResource(apiURL: string, httpHeaders?: { headers: HttpHeaders }): Observable<{}> {
64         const getRequest: APIURLHEADER = this.getHttpoptions(apiURL);
65         if (!isNullOrUndefined(httpHeaders)) {
66             return this.http.get(apiURL, httpHeaders);
67         } else {
68             return this.http.get(getRequest.url, getRequest.httpOptions);
69         }
70     }
71
72     /**
73      * Create a new resource on the server.
74      * @param apiURL The URL of the resource to be created.
75      * @param payload The request data to be sent to server.
76      */
77
78     public postResource(apiURLHeader: { url: string, httpOptions?: { headers: HttpHeaders } }, payload: {}): Observable<{}> {
79         const getRequest: APIURLHEADER = this.getHttpoptions(apiURLHeader.url);
80         if (!isNullOrUndefined(apiURLHeader.httpOptions)) {
81             return this.http.post(apiURLHeader.url, payload, apiURLHeader.httpOptions);
82         } else {
83             return this.http.post(getRequest.url, payload, getRequest.httpOptions);
84         }
85     }
86
87     /**
88      * Modify the resource on the server.
89      * @param apiURL The URL of the resource to be created.
90      * @param payload The request data to be sent to server.
91      */
92
93     public patchResource(apiURLHeader: { url: string, httpOptions?: { headers: HttpHeaders } }, payload: {}): Observable<object> {
94         const getRequest: APIURLHEADER = this.getHttpoptions(apiURLHeader.url);
95         if (!isNullOrUndefined(apiURLHeader.httpOptions)) {
96             return this.http.patch(apiURLHeader.url, payload, apiURLHeader.httpOptions);
97         } else {
98             return this.http.patch(getRequest.url, payload, getRequest.httpOptions);
99         }
100     }
101
102     /**
103      * Replace the resource on the server.
104      * @param apiName The URL of the resource to be created.
105      * @param payload The request data to be sent to server.
106      */
107
108     public putResource(apiURLHeader: { url: string, httpOptions?: { headers: HttpHeaders } }, payload: {}): Observable<object> {
109         const getRequest: APIURLHEADER = this.getHttpoptions(apiURLHeader.url);
110         if (!isNullOrUndefined(apiURLHeader.httpOptions)) {
111             return this.http.put(apiURLHeader.url, payload, apiURLHeader.httpOptions);
112         } else {
113             return this.http.put(getRequest.url, payload, getRequest.httpOptions);
114         }
115     }
116
117     /**
118      * Delete a resource identified by a URL.
119      * @param apiURL The URL of the resource to be deleted.
120      */
121
122     public deleteResource(apiURL: string, httpHeaders?: { headers: HttpHeaders }): Observable<object> {
123         const getRequest: APIURLHEADER = this.getHttpoptions(apiURL);
124         if (!isNullOrUndefined(httpHeaders)) {
125             return this.http.delete(apiURL, httpHeaders);
126         } else {
127             return this.http.delete(getRequest.url, getRequest.httpOptions);
128         }
129     }
130
131     /**
132      * Handle Error response based on the status.
133      * @param error The error response reecieved from API call.
134      * @param method The http request method.
135      */
136     // tslint:disable-next-line: cyclomatic-complexity
137     public handleError(err: ERRORDATA, method?: string): void {
138         if (err.error.status === HttpStatus.UNAUTHORIZED) {
139             if (method !== 'get') {
140                 if (err.error.detail !== 'Expired Token or Authorization HTTP header' &&
141                     err.error.detail !== 'Invalid Token or Authorization HTTP header') {
142                     this.notifierService.notify('error', err.error.detail !== undefined ?
143                         err.error.detail : this.translateService.instant('HTTPERROR.401'));
144                 }
145                 this.activeModal.dismissAll();
146             }
147         } else if (err.error.status === HttpStatus.BAD_REQUEST) {
148             this.notifierService.notify('error', err.error.detail !== undefined ?
149                 err.error.detail : this.translateService.instant('HTTPERROR.400'));
150         } else if (err.error.status === HttpStatus.NOT_FOUND) {
151             this.notifierService.notify('error', err.error.detail !== undefined ?
152                 err.error.detail : this.translateService.instant('HTTPERROR.404'));
153         } else if (err.error.status === HttpStatus.CONFLICT) {
154             this.notifierService.notify('error', err.error.detail !== undefined ?
155                 err.error.detail : this.translateService.instant('HTTPERROR.409'));
156             this.activeModal.dismissAll();
157         } else if (err.error.status === HttpStatus.INTERNAL_SERVER_ERROR) {
158             this.notifierService.notify('error', err.error.detail !== undefined ?
159                 err.error.detail : this.translateService.instant('HTTPERROR.500'));
160         } else if (err.error.status === HttpStatus.BAD_GATEWAY) {
161             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.502'));
162         } else if (err.error.status === HttpStatus.SERVICE_UNAVAILABLE) {
163             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.503'));
164         } else if (err.error.status === HttpStatus.GATEWAY_TIMEOUT) {
165             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.504'));
166         } else {
167             this.notifierService.notify('error', err.error.detail !== undefined ?
168                 err.error.detail : this.translateService.instant('ERROR'));
169         }
170     }
171
172     /** Set headers for get Methods @public */
173     private getHttpoptions(apiURL: string): APIURLHEADER {
174         const apiHeaders: HttpHeaders = new HttpHeaders({
175             'Content-Type': 'application/json; charset=UTF-8',
176             Accept: 'application/json',
177             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
178         });
179         return {
180             url: apiURL,
181             httpOptions: {headers : apiHeaders}
182         };
183     }
184 }