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