Files
FarmMapsLib/projects/common/src/fm/services/cache-service.ts
Willem Dantuma 8667001c01 Remove oauth
2026-03-25 21:08:18 +01:00

45 lines
1.3 KiB
TypeScript

import { Injectable } from '@angular/core';
import { Observable, ReplaySubject, Subscription, timer } from 'rxjs';
import { catchError, take } from 'rxjs/operators';
import { IItem } from '../models/item';
import { ItemService } from './item.service';
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) {
timer(0, REFRESH_INTERVAL).subscribe(() => {
this.subscriptionMap = {};
})
}
getItemList(itemType: string) : Observable<IItem[]> {
if (!this.proxyCacheMap[itemType]) {
this.proxyCacheMap[itemType] = new ReplaySubject(1);
}
if (!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)
);
}
}