Fix Bug 2121: NG-UI uses unmaintained Chokidar version
[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 { isNullOrUndefined } from 'util';
24 import { HttpClient, HttpHeaders } from '@angular/common/http';
25 import { Injectable } from '@angular/core';
26 import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
27 import { TranslateService } from '@ngx-translate/core';
28 import { NotifierService } from 'angular-notifier';
29 import { APIURLHEADER, ERRORDATA } from 'CommonModel';
30 import * as HttpStatus from 'http-status-codes';
31 import { Observable } from 'rxjs';
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     public handleError(err: ERRORDATA, method?: string): void {
137         if (err.error.status === HttpStatus.UNAUTHORIZED) {
138             if (method !== 'get') {
139                 if (err.error.detail !== 'Expired Token or Authorization HTTP header' &&
140                     err.error.detail !== 'Invalid Token or Authorization HTTP header') {
141                     this.notifierService.notify('error', err.error.detail !== undefined ?
142                         err.error.detail : this.translateService.instant('HTTPERROR.401'));
143                 }
144                 this.activeModal.dismissAll();
145             }
146         } else if (err.error.status === HttpStatus.BAD_REQUEST) {
147             this.notifierService.notify('error', err.error.detail !== undefined ?
148                 err.error.detail : this.translateService.instant('HTTPERROR.400'));
149         } else if (err.error.status === HttpStatus.NOT_FOUND) {
150             this.notifierService.notify('error', err.error.detail !== undefined ?
151                 err.error.detail : this.translateService.instant('HTTPERROR.404'));
152         } else if (err.error.status === HttpStatus.CONFLICT) {
153             this.notifierService.notify('error', err.error.detail !== undefined ?
154                 err.error.detail : this.translateService.instant('HTTPERROR.409'));
155             this.activeModal.dismissAll();
156         } else if (err.error.status === HttpStatus.INTERNAL_SERVER_ERROR) {
157             this.notifierService.notify('error', err.error.detail !== undefined ?
158                 err.error.detail : this.translateService.instant('HTTPERROR.500'));
159         } else if (err.error.status === HttpStatus.BAD_GATEWAY) {
160             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.502'));
161         } else if (err.error.status === HttpStatus.SERVICE_UNAVAILABLE) {
162             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.503'));
163         } else if (err.error.status === HttpStatus.GATEWAY_TIMEOUT) {
164             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.504'));
165         } else {
166             this.notifierService.notify('error', err.error.detail !== undefined ?
167                 err.error.detail : this.translateService.instant('ERROR'));
168         }
169     }
170
171     /** Set headers for get Methods @public */
172     private getHttpoptions(apiURL: string): APIURLHEADER {
173         const apiHeaders: HttpHeaders = new HttpHeaders({
174             'Content-Type': 'application/json; charset=UTF-8',
175             Accept: 'application/json',
176             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
177         });
178         return {
179             url: apiURL,
180             httpOptions: {headers : apiHeaders}
181         };
182     }
183 }