angelnikolov / ts-cacheable

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

Watching changes and busting cache for parameters #45

Closed muratcorlu closed 5 years ago

muratcorlu commented 5 years ago

I'll give an example code for telling what I need:

export class HeadlinesService extends ApiService<Headline> {
  basePath = 'headlines';

  checkForChanges(slotId: string) {
    this.makara.key('headlines', slotId).subscribe((msg) => {
      // TODO: invalidate cache for `getHeadlines` with this slotId
    })
  }

  @Cacheable()
  getHeadlines(slotId: string): Observable<Headline[]> {
    return this.list2({slot: slotId}).pipe(
      map((listResponse) => listResponse.map(headline => new Headline().cast(headline)))
    )
  }
}

That makara is a socket service that I can bind for the events for data chances in server. I need to run this binding once someone called getHeadlines and then want to bust cache for given slotId when I got an update from makara service. But I couldn't find a way to intercept cacheable to trigger checkForChanges method in first call and then invalidate the cache for given slotId. Can someone give me a tip for that need?

angelnikolov commented 5 years ago

The only way to do that is to implement a custom IStorageStrategy and call that explicitly in this method. In it, you can target the stored cache payload by slotId and remove it from your storage (in memory storage, local storage, redis or whatever) :)

frankdavidcorona commented 5 years ago

@angelnikolov, excellent work you save the day :-) only one simple request, could you provide some example to implement a custom IStorageStrategy, I want to use IndexDB.

angelnikolov commented 5 years ago

Right now there isn't an async storage strategy for the Cacheable decorator. So in a sense you can only cache synchronously - which IndexDB does not allow anymore. For now, you can switch to promises and use PCacheable which supports IAsyncStorageStrategy. You just need to implement the interface and provide all required methods. Then provide it globally to you decorators by assigning your storage strategy class to GlobalCacheConfig.storageStrategy. All that is in the docs :)