honojs/hono

[Feature Request]: `hono/cache` cacheName should also take function

Closed this issue · 3 comments

What is the feature you are proposing?

In the hono/cache middleware, how can we add query params or other variables from the context? Like caching the data based on different limit parameters or user profiles/roles.

I checked the code and it's a simple implementation, I can create a PR for this 😀

Echoing this! It seems like using the cache in conjunction with Cloudflare gets around this, but I imagine it would be helpful for other deployment locations where that isn't the case. It would also be more explicit as to what's happening.

@MathurAditya724

Nice! Like it.

I checked the code and it's a simple implementation, I can create a PR for this 😀

Please!

Echoing this! It seems like using the cache in conjunction with Cloudflare gets around this, but I imagine it would be helpful for other deployment locations where that isn't the case. It would also be more explicit as to what's happening.

While going through the code in more detail, I figured out why that was happening. Basically cacheName is a unique name for the collection of key-value stores and the URL (c.req.url) is used as the key to store those values. So as long as the values you want to use for the cache keys are in the URL, It is straightforward.

But in scenarios where you want to cache data conditionally like when certain parameters are present in the URL or the header, you will have to wrap a custom middleware around the cache.

@yusukebe I would suggest we have a keyGenerator function, which has a default value of (c) => c.req.url and if the returned key is undefined or null we will not cache it. Through this others can define their custom generator to tackle these issues in the future.