opt-cc/static/src/app/services/http-gateway.ts

79 lines
2.1 KiB
TypeScript

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<T>(url: string, searchParams?: HttpParams, getFullResponse = false): Observable<T> {
const options = this.createAuthorizationHeader();
if (searchParams) {
options['params'] = searchParams;
}
if (getFullResponse) {
options['observe'] = 'response';
}
return this.http.get<T>(url, options);
}
post<T>(url, data): Observable<T> {
return this.http.post<T>(url, data, this.createAuthorizationHeader());
}
put<T>(url, data): Observable<T> {
return this.http.put<T>(url, data, this.createAuthorizationHeader());
}
patch<T>(url, data): Observable<T> {
return this.http.patch<T>(url, data, this.createAuthorizationHeader());
}
delete(url) {
return this.http.delete(url, this.createAuthorizationHeader());
}
request<T>(requestUrl, body, method: HttpMethod): Observable<T> {
switch (method) {
case 'GET':
return this.get(requestUrl);
case 'POST':
return this.post<T>(requestUrl, body);
case 'PUT':
return this.put(requestUrl, body);
case 'PATCH':
return this.patch<T>(requestUrl, body);
}
}
}