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

79 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-03-07 11:56:50 +01:00
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';
2017-05-10 11:04:06 +02:00
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH'
2017-05-10 11:04:06 +02:00
@Injectable()
export class HttpGateway {
2017-05-10 11:04:06 +02:00
constructor(private router: Router,
private http: HttpClient,
2017-09-23 11:53:10 +02:00
private cookieService: CookieService) {
2017-05-10 11:04:06 +02:00
}
createAuthorizationHeader() {
2017-09-23 12:05:51 +02:00
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 {
2018-03-07 11:56:50 +01:00
// logout
2017-07-27 16:38:35 +02:00
localStorage.removeItem('currentUser');
2018-03-07 11:56:50 +01:00
this.router.navigate(['/login']);
}
} else {
return {};
2017-05-10 11:04:06 +02:00
}
}
get<T>(url: string, searchParams?: HttpParams, getFullResponse = false): Observable<T> {
const options = this.createAuthorizationHeader();
2017-05-10 11:04:06 +02:00
if (searchParams) {
options['params'] = searchParams;
}
if (getFullResponse) {
options['observe'] = 'response';
2017-05-10 11:04:06 +02:00
}
return this.http.get<T>(url, options);
2017-05-10 11:04:06 +02:00
}
post<T>(url, data): Observable<T> {
return this.http.post<T>(url, data, this.createAuthorizationHeader());
2017-05-10 11:04:06 +02:00
}
put<T>(url, data): Observable<T> {
return this.http.put<T>(url, data, this.createAuthorizationHeader());
2017-05-13 14:57:40 +02:00
}
patch<T>(url, data): Observable<T> {
return this.http.patch<T>(url, data, this.createAuthorizationHeader());
2017-05-10 11:04:06 +02:00
}
delete(url) {
return this.http.delete(url, this.createAuthorizationHeader());
2017-05-10 11:04:06 +02:00
}
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);
2017-05-10 11:04:06 +02:00
}
}
}