import {Injectable} from '@angular/core'; import {Router} from '@angular/router'; import {CookieService} from 'ngx-cookie-service'; import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; import {Observable} from 'rxjs'; export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' @Injectable() export class HttpGateway { constructor(private router: Router, private http: HttpClient, private cookieService: CookieService) { } createAuthorizationHeader() { const cookieField = this.cookieService.get('currentUser'); if (cookieField) { const currentUser = JSON.parse(cookieField); if (new Date().getTime() <= Date.parse(currentUser.tokenExpireDate)) { return { headers: new HttpHeaders({ 'x-access-token': currentUser.token }) }; } else { // logout localStorage.removeItem('currentUser'); this.router.navigate(['/login']); } } else { return {}; } } get(url: string, searchParams?: HttpParams, getFullResponse = false): Observable { const options = this.createAuthorizationHeader(); if (searchParams) { options['params'] = searchParams; } if (getFullResponse) { options['observe'] = 'response'; } return this.http.get(url, options); } post(url, data): Observable { return this.http.post(url, data, this.createAuthorizationHeader()); } put(url, data): Observable { return this.http.put(url, data, this.createAuthorizationHeader()); } patch(url, data): Observable { return this.http.patch(url, data, this.createAuthorizationHeader()); } delete(url) { return this.http.delete(url, this.createAuthorizationHeader()); } request(requestUrl, body, method: HttpMethod): Observable { switch (method) { case 'GET': return this.get(requestUrl); case 'POST': return this.post(requestUrl, body); case 'PUT': return this.put(requestUrl, body); case 'PATCH': return this.patch(requestUrl, body); } } }