cic-staff-client/src/app/_services/http-wrapper.service.ts

61 lines
1.9 KiB
TypeScript

import { Injectable } from '@angular/core';
import {HttpClient, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import * as moment from 'moment';
import { Moment } from 'moment';
import {LoggingService} from '@app/_services/logging.service';
@Injectable({
providedIn: 'root'
})
export class HttpWrapperService {
constructor(
private http: HttpClient,
private loggingService: LoggingService,
) { }
get(url: string, options?: any): Observable<Response> {
return this.request('GET', url, null, options);
}
post(url: string, body: any, options?: any): Observable<Response> {
return this.request('POST', url, body, options);
}
put(url: string, body: any, options?: any): Observable<Response> {
return this.request('PUT', url, body, options);
}
delete(url: string, options?: any): Observable<Response> {
return this.request('DELETE', url, null, options);
}
private logTime(startMoment: Moment, url: string, method: string): void {
const requestDuration = moment().diff(startMoment, 'milliseconds');
this.loggingService.sendInfoLevelMessage(`HTTP ${method}, URL: ${url}, Duration: ${requestDuration} ms`);
}
private request(method: string, url: string, body?: any, options?: any): Observable<any> {
this.loggingService.sendInfoLevelMessage(`Options: ${options}`);
return Observable.create((observer: any) => {
const requestBeginTime = moment();
this.http.request(new HttpRequest(method, url, body, options)).subscribe((response) => {
this.loggingService.sendInfoLevelMessage(response);
this.logTime(requestBeginTime, `${url}`, method);
observer.next(response);
observer.complete();
}, (error) => {
switch (error.status) {
case 403:
observer.complete();
break;
default:
observer.error(error);
break;
}
});
});
}
}