Shared services
Some checks failed
FarmMaps.Develop/FarmMapsLib/pipeline/head There was a failure building this commit
Some checks failed
FarmMaps.Develop/FarmMapsLib/pipeline/head There was a failure building this commit
This commit is contained in:
44
projects/common/src/fm/services/cache-service.ts
Normal file
44
projects/common/src/fm/services/cache-service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { IItem, ItemService } from '@farmmaps/common';
|
||||
import { OAuthService } from 'angular-oauth2-oidc';
|
||||
import { Observable, ReplaySubject, Subscription, timer } from 'rxjs';
|
||||
import { catchError, take } from 'rxjs/operators';
|
||||
|
||||
const REFRESH_INTERVAL = 15 * 60 * 1000; // 15m
|
||||
|
||||
@Injectable({ providedIn: 'root'})
|
||||
export class CacheService {
|
||||
private proxyCacheMap: { [key: string]: ReplaySubject<IItem[]> } = {};
|
||||
private subscriptionMap: { [key: string]: Subscription } = {};
|
||||
|
||||
constructor(private itemService: ItemService, public oauthService: OAuthService) {
|
||||
timer(0, REFRESH_INTERVAL).subscribe(() => {
|
||||
this.subscriptionMap = {};
|
||||
})
|
||||
}
|
||||
|
||||
getItemList(itemType: string) : Observable<IItem[]> {
|
||||
if (!this.proxyCacheMap[itemType]) {
|
||||
this.proxyCacheMap[itemType] = new ReplaySubject(1);
|
||||
}
|
||||
|
||||
if (this.oauthService.getAccessToken() != null && !this.subscriptionMap[itemType]) {
|
||||
this.subscriptionMap[itemType] = this.itemService.getItemList(itemType)
|
||||
.pipe(
|
||||
catchError(error => {
|
||||
this.subscriptionMap[itemType].unsubscribe();
|
||||
this.subscriptionMap[itemType] = null;
|
||||
throw error;
|
||||
}),
|
||||
|
||||
).subscribe(items => {
|
||||
this.proxyCacheMap[itemType].next(items);
|
||||
});
|
||||
}
|
||||
|
||||
return this.proxyCacheMap[itemType].asObservable()
|
||||
.pipe(
|
||||
take(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user