angelnikolov / ts-cacheable

Observable/Promise Cache Decorator
https://npmjs.com/package/ts-cacheable
ISC License
340 stars 42 forks source link

CacheBuster only working after 2nd call #79

Closed kirstenfrager closed 4 years ago

kirstenfrager commented 4 years ago

I have implemented a PCacheBuster which is only busting the cache the second time I trigger my function.

service.ts

  @PCacheable({
    maxAge: CachingMinuteEnum.TWO_MIN,
    maxCacheCount: 5, // for pagination: will allow 5 different page data stored before cache cleared
    cacheBusterObserver: getNearbyAdvertsCacheBuster$,
    shouldCacheDecider: response => Object.keys(response.data).length > 0,
  })
  getNearbyAdverts(pageSize: number = 10, pageNumber: number = 1, isMore?: boolean): Promise<any> {
    return this._httpService.get(`/advert/bygeo/${this._fencingService.getCountry()}/${this._fencingService.getGeoUrlParams(SortingEnum.DISTANCE)}/${pageSize}/${pageNumber}`, true, isMore).toPromise();
  }

base.ts

  @PCacheBuster({
    cacheBusterNotifier: getNearbyAdvertsCacheBuster$
  })
  radiusChangeData() {
    return this.getAndSetData();
  }

The radiusChangeData() function gets triggered when the user changes their location radius (which in turn I want to bust the cache so that new data can be returned within the newly selected radius). The first time the user changes the radius the function gets called but nothing happens, the second time they select it I can see the new data being returned.

What I imagine is happening is that on page load my data get gets cached. On the first radiusChangeData() call I am busting the cache, but then this function has to be called again so that the new data comes back? Is this what seems to be happening?

If so, how can I bust the cache and call the function at the same time with the new data?

angelnikolov commented 4 years ago

@kirstenfrager Sorry for the late answer. I noticed this method getAndSetData. Does it by any chance first get the data and then set it (calling the POST endpoint)? If so, that might be the issue. The cache will be busted by the getNearbyAdvertsCacheBuster$ subject only when radiusChangeData() completes (i.e its promise has resolved). Maybe you get the data before that?

deyanpeychev00 commented 4 years ago

@kirstenfrager how you've implemented the cache duration enumeration object CachingMinuteEnum.TWO_MIN ?