stash-it-plugin-ttl

1.1.0 • Public • Published

logo-stash-it-color-dark 2x

stash-it-plugin-ttl

build status Coverage Status

TTL plugin for stash-it.

Installation

npm i stash-it-plugin-ttl --save

Usage

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'); // false

Heads 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

Package Sidebar

Install

npm i stash-it-plugin-ttl

Weekly Downloads

1

Version

1.1.0

License

MIT

Unpacked Size

8.63 kB

Total Files

4

Last publish

Collaborators

  • jaceks