41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { Observable } from 'rxjs/Observable';
|
|
import { tap } from 'rxjs/operators';
|
|
import { CacheApiKey } from '../models/cache-api-key.enum';
|
|
import { of } from 'rxjs';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class ServiceCacheApi {
|
|
private cache: Map<CacheApiKey, Observable<any>>;
|
|
|
|
constructor() {
|
|
this.cache = new Map<CacheApiKey, Observable<any>>();
|
|
}
|
|
|
|
public get<T>(key: CacheApiKey, callToApi: Observable<T>) : Observable<T> {
|
|
// console.log(`Get/push cache : ${CacheApiKey[key]}`);
|
|
const cached = this.cache.get(key);
|
|
|
|
if (cached) {
|
|
return cached;
|
|
} else {
|
|
return callToApi.pipe(
|
|
tap(event => {
|
|
this.cache.set(key, of(event));
|
|
}));
|
|
}
|
|
}
|
|
|
|
public delete(key: CacheApiKey) {
|
|
// console.log(`Delete cache : ${CacheApiKey[key]}`);
|
|
this.cache.delete(key);
|
|
}
|
|
|
|
public getByKey<T>(key: CacheApiKey) : Observable<T> {
|
|
// console.log(`Get cache by key : ${CacheApiKey[key]}`);
|
|
return this.cache.get(key);
|
|
}
|
|
}
|