angelnikolov / ts-cacheable

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

Support for optional parameters #130

Closed geraparra closed 1 year ago

geraparra commented 1 year ago

Hi,

I'm facing an issue when using optional parameters.

This an example of the method definition:

@Cacheable() getSpareLocations(locationId?: number, partId?: number): Observable { .... return this.http.get(this.apiEndpointService.getSpareLocationEndpoint(), httpParams); }

I reuse and call this method in differente screens with different parameter values but always the same order and values:

Screen 1:

this.spareLocationService .getSpareLocations(locationId, undefined) // here you can get a spare location only by locationid so stockid is always undefined.

Screen 2:

const stockId = undefined; this.spareLocationService .getSpareLocations(locationId, stockId) // here you can get a spare location by locationid or by stockid.

When calling the method I need to explicity add the optional parameter undefined as in the example in screen 1 because if I call the method without expliciting the default parameter for example:

this.spareLocationService.getSpareLocations(locationId)

the method doesn't share the cache despite the parameters are the same. (number, undefined).

I don't want to explicity add the optional parameter undefined, so I'm asking if is there any solution for this behavior?

Regards,

Gerardo.

angelnikolov commented 1 year ago

@geraparra So, the way we figure out what the cacheKey is (the thing which we use to search for cache) is by using a hasher function, which takes your parameters and creates the key on every call, based on the parameters. The default one is this

export const DEFAULT_HASHER = (parameters: Array<any>) => parameters.map(param => param !== undefined ? JSON.parse(JSON.stringify(param)) : param);

As you can see, we are checking for undefined there. So I suggest you just add your own hasher which doesnt do that by either providing the cacheHasher property to your decorator https://github.com/angelnikolov/ts-cacheable#configuration, or adding that to the GlobalCacheConfig GlobalCacheConfig

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.