import { HttpClient, HttpHeaders } from '@angular/common/http'; /** * Created by cabbar on 19.04.2017. */ import { Injectable } from '@angular/core'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; import { Observable } from 'rxjs/Rx'; import { DnResultBase } from '../model'; import { DnResultDataBase } from '../model/http-result-data-base'; import { isNullOrUndefined } from '../utils/check'; import { deepCopy } from '../utils/copy'; import { DnHttpExtraConfig, IDnHttpExtraConfig } from './http-result-extra.config'; import { DnNotificationService } from './notification.service'; import { DnStorageService } from './storage.service'; import { DnTokenService } from './token.service'; @Injectable() export class DnHttpService { private token: string; private readonly cachableHttpUrlsKey = 'httpEnums'; private defaultConfig: IDnHttpExtraConfig = { useApi: true, loadingBase: null, useToken: true, id: 0 }; // cacheHttp: Map = new Map(); // cachableHttpUrls: string[] = []; constructor(private http: HttpClient, private _tokenService: DnTokenService, private _storage: DnStorageService, // private _router: Router, private _nf: DnNotificationService) { } addCachableUrl(url: string) { url = url.toLowerCase(); if (!this.isCachable(url)) { this.addCachableArray(url); } return this; } delete(url: string, id: any, extra?: IDnHttpExtraConfig): Observable | Response | {}> { extra = this.getConfig(extra); this.showLoading(extra); return this.http.delete(`${this.getUrl(url)}/${id}`, this.getHeaderOptions(extra)) .map((res: Response | DnResultDataBase) => { this.hideLoading(extra); return res; }) .catch(this.showErrorMessage.bind(this)); } get(url: string, extra?: IDnHttpExtraConfig): Observable> { extra = this.getConfig(extra); this.showLoading(extra); const isCachable = this.isCachable(url); console.log('HTTP Service url : ' + url + ' isCachable : ', isCachable); if (isCachable && this._storage.hasItem(url.toLowerCase())) { return Observable.of(this._storage.getItem(url.toLowerCase(), false)); } const obs = this.http.get>(this.getUrl(url, extra), this.getHeaderOptions(extra)); if (extra.useMap) { return obs.map((res: DnResultDataBase) => { if (this.isCachable(url) && !this._storage.hasItem(url.toLowerCase())) { this._storage.setItem(url.toLowerCase(), res, false); } this.hideLoading(extra); return res; }).catch(err => { this.hideLoading(extra); return this.showErrorMessage(err); }); } else { if (isCachable) { return obs.map((res: DnResultDataBase) => { this._storage.setItem(url.toLowerCase(), res, false); return res; }).catch(err => { return this.showErrorMessage(err); }); } else { return obs; } } } getCachableArray(): string[] { const arr = this._storage.getItem(this.cachableHttpUrlsKey); if (isNullOrUndefined(arr)) { return []; } return arr; } post(body: object, url: string, extra?: IDnHttpExtraConfig): Observable> { extra = this.getConfig(extra); this.showLoading(extra); return this.http.post(this.getUrl(url, extra), body, this.getHeaderOptions(extra)) .map((res: Response) => { this.hideLoading(extra); return res; }) .catch(err => { this.hideLoading(extra); return Observable.throw(err.error || 'Server error'); }); } put(body: object, url?: string, extra?: IDnHttpExtraConfig): Observable> { extra = this.getConfig(extra, body['id']); this.showLoading(extra); return this.http.put(this.getUrl(url, extra), JSON.stringify(body), this.getHeaderOptions(extra)) .map((res: Response) => { this.hideLoading(extra); return res; }) .catch(err => { this.hideLoading(extra); return this.showErrorMessage(err); }); } refreshCache(url?: string) { if (url) { const _url = url.toLowerCase(); this._storage.removeItem(_url); this.get(_url).subscribe(val => { if (val && val.isSuccess) { this._storage.setItem(_url, val, false); } }); } else { this.getCachableArray().forEach(item => this._storage.removeItem(item)); const $tasks = []; for (let i = 0; i < this.getCachableArray().length; i++) { const _url = this.getCachableArray()[i].toLowerCase(); this._storage.removeItem(_url); $tasks.push(this.get(_url)); } Observable.forkJoin(...$tasks).subscribe((items: DnResultBase[]) => { for (let i = 0; i < items.length; i++) { if (items[i] && items[i].isSuccess) { this._storage.setItem(this.getCachableArray()[i], items[i], false); } } }); } return this; } reset() { this.token = null; } private addCachableArray(value) { const arr = this.getCachableArray(); arr.push(value); this._storage.setItem(this.cachableHttpUrlsKey, arr); } private getConfig(extra?: IDnHttpExtraConfig, id?: number): IDnHttpExtraConfig { extra = !extra ? deepCopy(this.defaultConfig) : new DnHttpExtraConfig(extra); if (id) { extra.id = id; } return extra; } private getHeaderOptions(extra: IDnHttpExtraConfig) { let headers; if (extra && !extra.useToken) { headers = new HttpHeaders({ 'Content-Type': 'application/json' }); } else { headers = new HttpHeaders({ 'Content-Type': 'application/json', Authorization: `Bearer ${this._tokenService.getToken()}` }); } return {headers}; } private getToken(): string { if (!this.token) { this.token = this._tokenService.getToken(); } return this.token; } private getUrl(url: string, extra?: IDnHttpExtraConfig): string { let _url = ''; if (extra) { if (extra.useApi) { _url += 'api/'; } _url += url; if (extra.id) { _url += `/${extra.id}`; } } else { _url = `api/${url}`; } return _url; } private hideLoading(extra: IDnHttpExtraConfig) { if (extra && extra.loadingBase) { extra.loadingBase.loading = false; } } private isCachable(url: string): boolean { return this.getCachableArray().filter(l => l == url.toLowerCase()).length > 0; } private showErrorMessage(err: any): ErrorObservable { if (err.status == 401) { this._nf.showWarning('Oturumunuz düşmüştür. Giriş Sayfasına yönlendiriliyorsunuz'); // setTimeout(() => this._router.navigate(['/auth/login']), 2000); } else { this._nf.showError('Servis tarafında bir hata oluştu. Sistem yöneticisine başvurunuz. Hata Kodu: ' + err.status); } return Observable.throw(err.error || 'Server error'); } private showLoading(extra: IDnHttpExtraConfig) { if (extra && extra.loadingBase) { extra.loadingBase.loading = true; } } }