1.1.0 • Published 7 years ago
stash-it-plugin-ttl v1.1.0

stash-it-plugin-ttl
TTL plugin for stash-it.
Installation
npm i stash-it-plugin-ttl --saveUsage
import { createCache } from 'stash-it';
import createTtlPlugin from 'stash-it-plugin-ttl';
// You can use any adapter
import createMemoryAdapter from 'stash-it-adapter-memory';
const cache = createCache(createMemoryAdapter());
const ttlPlugin = createTtlPlugin();
const cacheWithPlugin = cache.registerPlugins([ ttlPlugin ]);
// Store item with `ttl` in `extra`
const oneHourInSeconds = 3600;
cacheWithPlugin.setItem('key', 'value', { ttl: oneHourInSeconds });
cacheWithPlugin.hasItem('key'); // true
// ... one hour has passed
cacheWithPlugin.hasItem('key'); // falseHeads up: ttl is being moved from extra's top level structure,
so that it is only available in ttlData.
Invalidation of cache
Plugin will invalidate (remove) the item, if ttl has ended, upon:
- checking if item exists using
hasItem - getting the item using
getItem
ttlData structure
ttlData = {
ttl: durationInSeconds,
created: dateTime,
validTill: dateTime
}Important: ttlData is immutable (using Object.freeze).
touch(key)
This is an additional method, that the plugin will extend the cache instance with.
Using it, on a given item, represented by its key, will refresh the
validTill property in ttlData stored in extra of that item.
Returns ttlData with updated validTill value upon success.
If item is not present or item doesn't have ttlData in extra - returns false.
If you try to touch an item that does not exist, this method will
return false.
Example (using the cacheWithPlugin from above):
// let's store the item again
cacheWithPlugin.setItem('key', 'value', { ttl: oneHourInSeconds });
cacheWithPlugin.hasItem('key'); // true
// 59 minutes have passed
cacheWithPlugin.touch('key');
// 2 minutes have passed (61 in total)
cacheWithPlugin.hasItem('key'); // true