Skip to content

Instantly share code, notes, and snippets.

@captainkovalsky
Created March 1, 2017 09:11
Show Gist options
  • Save captainkovalsky/6149f641b6c7e0bd0a079857247bd207 to your computer and use it in GitHub Desktop.
Save captainkovalsky/6149f641b6c7e0bd0a079857247bd207 to your computer and use it in GitHub Desktop.
import { Observable } from '../../../../projects/demo-portal-angular/src/main/storefront-spa-webapp/node_modules/rxjs/Observable';
class CacheApi {
private cachedStream: Observable;
protected cached: boolean = false;
public setCache(stream: Observable<any>) {
this.cachedStream = stream.share();
this.cached = true;
}
public getCache(): Observable<any> {
return this.cachedStream;
}
public get cached(): boolean {
return this.cached;
}
}
const cacheMap = new WeakMap();
export function cache(TTL = 1000 * 60 * 10): Function {
return function (target: any, propertyKey: any, descriptor: any) {
setTimeout(() => {
cacheMap.delete(property);
}, TTL);
return _.memoize(target[property]);
}
}
class Api {
@cache()
fetchOrders(): Observable<number> {
return Observable.of(1);
}
}
class Api2 extends CacheApi {
constructor() {
super(this);
}
fetchOrders(): Observable<number> {
if (!this.cached) {
let stream = Observable.of(1);
this.setCache(stream);
}
return this.getCache();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment