d3d9ea0d26ec1edf81e3a1a4305c4fdc10044092
[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             } else {
145                 this.notifierService.notify('error', err?.error?.detail !== undefined ?
146                     err?.error?.detail : this.translateService.instant('HTTPERROR.401'));
147             }
148             this.activeModal.dismissAll();
149         } else if (err.error.status === HttpStatus.BAD_REQUEST) {
150             this.notifierService.notify('error', err.error.detail !== undefined ?
151                 err.error.detail : this.translateService.instant('HTTPERROR.400'));
152         } else if (err.error.status === HttpStatus.NOT_FOUND) {
153             this.notifierService.notify('error', err.error.detail !== undefined ?
154                 err.error.detail : this.translateService.instant('HTTPERROR.404'));
155         } else if (err.error.status === HttpStatus.CONFLICT) {
156             this.notifierService.notify('error', err.error.detail !== undefined ?
157                 err.error.detail : this.translateService.instant('HTTPERROR.409'));
158             this.activeModal.dismissAll();
159         } else if (err.error.status === HttpStatus.INTERNAL_SERVER_ERROR) {
160             this.notifierService.notify('error', err.error.detail !== undefined ?
161                 err.error.detail : this.translateService.instant('HTTPERROR.500'));
162         } else if (err.error.status === HttpStatus.BAD_GATEWAY) {
163             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.502'));
164         } else if (err.error.status === HttpStatus.SERVICE_UNAVAILABLE) {
165             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.503'));
166         } else if (err.error.status === HttpStatus.GATEWAY_TIMEOUT) {
167             this.notifierService.notify('error', this.translateService.instant('HTTPERROR.504'));
168         } else {
169             this.notifierService.notify('error', err.error.detail !== undefined ?
170                 err.error.detail : this.translateService.instant('ERROR'));
171         }
172     }
173
174     /** Set headers for get Methods @public */
175     private getHttpoptions(apiURL: string): APIURLHEADER {
176         const apiHeaders: HttpHeaders = new HttpHeaders({
177             'Content-Type': 'application/json; charset=UTF-8',
178             Accept: 'application/json',
179             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
180         });
181         return {
182             url: apiURL,
183             httpOptions: { headers: apiHeaders }
184         };
185     }
186 }