angelnikolov / ts-cacheable

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

Feat/remove serialization #55

Closed angelnikolov closed 4 years ago

angelnikolov commented 4 years ago

@iherwig @SansDK Please check this PR. It introduces a custom cacheHasher configuration which allows to pass a custom hash function which will be used to calculate the cacheKey for a method call, based on the passed parameters. The default cache hasher is still using JSON.parse(JSON.stringify(parameters)) but the parameters passed to the original function will no longer be mutated. Please test it out if you can and let me know if it works for you, it is published in NPM as beta here.

SansDK commented 4 years ago

This works for me, thanks a lot! I now pass a custom cacheHasher to the @Cacheable decorator.

As a complete example, I use it like this:

@Cacheable({
  maxAge: 3600000,
  cacheHasher: (parameters: Array<any>) =>
    parameters.map(param =>
      param !== undefined
        ? JSON.parse(JSON.stringify(param, (key, value) => {
            if (key === '_meta') {return undefined; }
            else {return value; }}))
        : param
    )
})

This way, it ignores the _meta property in the JSON object, which solves my recursive JSON issue.

Is this the correct way to use the new feature in this PR?

angelnikolov commented 4 years ago

@SansDK, yes this is the correct way :)

iherwig commented 4 years ago

This works well for me too. Thank you!