argos/dmp-frontend/src/app/services/help-content/help-content.service.ts

56 lines
2.2 KiB
TypeScript
Raw Normal View History

2018-02-16 08:45:18 +01:00
/**
* Created by stefania on 7/17/17.
*/
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { PageHelpContent } from '../../models/help-content/page-help-content';
2018-02-16 11:34:02 +01:00
import { CachedContentItem } from './CachedContentItem';
import { HostConfiguration } from '../../app.constants';
2018-02-16 08:45:18 +01:00
@Injectable()
export class HelpContentService {
2018-03-06 15:58:38 +01:00
private _helpServiceUrl = HostConfiguration.HelpServiceUrl;
2018-02-16 11:34:02 +01:00
cache = new Map<String, CachedContentItem>();
constructor(private http: Http) {
2018-02-16 08:45:18 +01:00
}
2018-02-16 11:34:02 +01:00
2018-02-16 08:45:18 +01:00
getActivePageContent(route: string) {
2018-02-16 11:34:02 +01:00
if (!this.cache.get(route) || !this.isValidCachedItem(route)) {
return this.http.get(this._helpServiceUrl + "/page/route?q=" + route)
.map(res => {
this.cache.set(route, { timestamp: Date.now(), content: <PageHelpContent>res.json() })
return res.json();
})
2018-02-16 08:45:18 +01:00
.catch(this.handleError)
}
2018-02-16 11:34:02 +01:00
return Observable.create(observer => observer.next(this.cache.get(route).content));
2018-02-16 08:45:18 +01:00
}
private extractData(res: Response) {
let body = res.json();
2018-02-16 11:34:02 +01:00
return body.data || {};
2018-02-16 08:45:18 +01:00
}
2018-02-16 11:34:02 +01:00
private handleError(error: Response | any) {
2018-02-16 08:45:18 +01:00
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = "";
console.log(error);
if (error instanceof Response) {
const body = error.text() || '';
//const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${body}`;
} else {
errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
}
return Observable.throw(errMsg);
}
2018-02-16 11:34:02 +01:00
isValidCachedItem(route) {
let cachedTimestamp = this.cache.get(route).timestamp;
let currentTimestamp = Date.now();
if (currentTimestamp - cachedTimestamp > HostConfiguration.CacheLifeTimeMillis) return false;
else return true;
}
2018-02-16 08:45:18 +01:00
}