angelnikolov / ts-cacheable

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

Don't cache if response is empty #61

Closed Patricksirich closed 4 years ago

Patricksirich commented 4 years ago

Hi! First of: I freaking love this package, thank you for sharing it!!!

And now to the issue: I currently have an issue where if the response is empty (no errors, just an empty response), the data is still cached.

It is highly unlikely that the API is returning an empty response, but it can happen.

I am already doing checks on empty data, wrong data, etc.

I would like to avoid busting the cache if the response is empty. Is there a clever way to ensure that the response is not saved if it is empty? And maybe the possibility of adding this as a configuration in the future?

angelnikolov commented 4 years ago

Hey @Patricksirich, thanks for your kind words! You can do this right now by passing a shouldCacheDecider to the decorator :)

Patricksirich commented 4 years ago

Thanks for the quick reply! What value should I give the shouldCacheDecider? Can't really seem to figure it out 😄

angelnikolov commented 4 years ago

It's a callback which takes the response and based on it will decide to cache it or not. For example, you could pass it as : shouldCacheDecider: response => response.length which would tell it to only cache the response if it is a non-empty array.

Patricksirich commented 4 years ago

That makes perfect sense, works like a charm, thanks!

Patricksirich commented 4 years ago

It doesn't seem to be working when maxCacheCount has been set. Currently my decorator looks like:

  @Cacheable({
    maxCacheCount: 3,
    maxAge: 300000,
    slidingExpiration: true,
    shouldCacheDecider: response => response.length
  })

but it does work on:

@Cacheable({
    maxAge: 300000,
    slidingExpiration: true,
    shouldCacheDecider: response => response.length
  })

Am I missing/have I misunderstood something?

EDIT: The issue is not the maxCacheCount but the paramater.

EDIT EDIT: I am blind... I was receiving a JSON object, which of course you cannot do a response.length on, so changed it to:

    shouldCacheDecider:  response => Object.keys(response).length > 0 

Aaaand it works.