Hapi: How to drop a cache key using server.method?

Created on 18 Apr 2015  路  5Comments  路  Source: hapijs/hapi

Just as the title says. How can I drop a cache using serving.method. I can't seem to find it on the documentation.

support

Most helpful comment

Easy way to get answers is in code:

https://github.com/hapijs/hapi/blob/e8dcc42c909a22acb335d7b1c86ee5baa34b8c12/lib/methods.js#L125-L165

There's no automatic way of dropping all cached results for a method. Think of generateKey as a one way hash function (like you'd use to hash passwords). Given a function and a set of arguments, you can hash those arguments using the function's generateKey to either get or delete data.

There is never a way to drop all keys short of resetting the entire cache. It sounds like you're using caching in a place that doesn't necessarily merit it. Good SQL databases typically have strong caching layers and are a bad optimization target, whereas external APIs w/ latency and rate limit concerns are usually good targets for optimization.

All 5 comments

When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key

http://hapijs.com/api#servermethodname-method-options

Thanks. I missed that part though. Quick question @bendrucker, does the key it generate still comes from generateKey function?

Yes! The awesome thing about Hapi is how clear and well organized the source is. Best way to get a good grasp on this is just to give it a read since it's barely 10 lines:

https://github.com/hapijs/hapi/blob/e8dcc42c909a22acb335d7b1c86ee5baa34b8c12/lib/methods.js#L147-L162

@bendrucker I was wondering though, suppose I query the same model BUT with different query parameters. Example:
query 1: /user?sort=createdAt
query 2: /user?page=2
and I cache both of the query. Then I decide to add a user, how can I drop both of the keys simultaneously?

Easy way to get answers is in code:

https://github.com/hapijs/hapi/blob/e8dcc42c909a22acb335d7b1c86ee5baa34b8c12/lib/methods.js#L125-L165

There's no automatic way of dropping all cached results for a method. Think of generateKey as a one way hash function (like you'd use to hash passwords). Given a function and a set of arguments, you can hash those arguments using the function's generateKey to either get or delete data.

There is never a way to drop all keys short of resetting the entire cache. It sounds like you're using caching in a place that doesn't necessarily merit it. Good SQL databases typically have strong caching layers and are a bad optimization target, whereas external APIs w/ latency and rate limit concerns are usually good targets for optimization.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hbinduni picture hbinduni  路  5Comments

foobar1123 picture foobar1123  路  3Comments

mahnunchik picture mahnunchik  路  4Comments

DrMabuse23 picture DrMabuse23  路  5Comments

kevinsimper picture kevinsimper  路  4Comments