Is there any way to set the cache segment dynamically?
bneigher opened this issue · 6 comments
Use Case: I want to have multiple cache segments, one for users, and for example one for precipitation probabilities by region. How would I go about having two cache segments?
My ideal situation would be if I could set the segment when calling get/set..
Example:
...
fastify.register(FastifyCache, { privacy: "private", expiresIn: 1000 * 60 * 60 });
...
let user;
user = fastify.cache.kv.get(req.user.sub);
if (!user) {
const userModel = await Users.findOrCreate({
where: { key: req.user.sub }
});
fastify.cache.kv.set(req.user.sub, userModel[0]); // 1hr default
user = fastify.cache.kv.get(req.user.sub);
}
req.auth = user;let location = location;
let probabilityPrecip = fastify.cache.kv.get(location);
if (!probabilityPrecip){
const newProbabilityPrecip = await Precipitation.get(location);
fastify.cache.kv.set(location, newProbabilityPrecip); // 1hr default
probabilityPrecip = fastify.cache.kv.get(location);
}
req.prob = probabilityPrecipIn this example - I would ideally have a separate segment for each store... namely:
fastify.cache.kv.get(user)
fastify.cache.kv.get(uset, { cacheSegment: 'users' })
fastify.cache.kv.get(location)
fastify.cache.kv.get(location, { cacheSegment: 'locations' })
I tried this and it doesn't seem to be possible given the signatures of get / set
set:
set (key,val,ttl=0,cb=function () {...
get:
get(key){...
Any ideas how to accomplish this? I don't think I can register a second cache in fastify since the fastify.cache namespace is hardcoded in the lib
In Fastify-land, we would accomplish this via encapsulation. You'd register one set of routes, e.g. "user" routes, in one encapsulation context with its own instance of the caching plugin. Then you'd register a completely new set of routes and a new instance of the plugin in another encapsulation context.
According to https://www.npmjs.com/package/abstract-cache (the cache client):
In all cases where a key is required, the key may be a simple string, or it may be an object of the format {id: 'name', segment: 'name'}. It is up to the implementing strategy to decide how to handle these keys.
Is this feature not compatible with the client implementation?
@jsumners ah, but what if we need to interact with both segments of the cache in the same route?
PRs are welcome.
Seems easy enough
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.