A simple memory cache with automatic invalidation after TTL. Runs on the browser and node
# npm
npm install sma-cache
# yarn
yarn add sma-cache
# pnpm
pnpm install sma-cache
import simpleCache from "sma-cache";
var TTL = 5000; // 5s
var cache = simpleCache(TTL);
var cacheItem = { greeting: "Hello World!" };
var key = "a-random-key";
cache.set(key, cacheItem);
The cacheItem
will automatically invalidate after TTL, so that:
// using a delay mechanism
delay(TTL);
cache.get(key); // => undefined
import simpleCache from "sma-cache";
import delay from "delay";
const cache = simpleCache(10);
function doSomething() {
const now = Date.now();
cache.set("time", now);
// after 0 s
delay(0).then(() => {
console.log(cache.get("time")); //=> now
});
// after 5 s
delay(5000).then(() => {
console.log(cache.get("time")); //=> now
});
// after 10 s
delay(10000).then(() => {
console.log(cache.get("time")); //=> undefined
});
}
doSomething();
Returns a cache object
which exposes methods to interact with the cache
Time in milliseconds before the item stored with key: random-key
is invalidated
Type: number
Default: 6000
The cache object exposes the following API
- set(key, options): store an item in the cache
- key: the key for the cache item
Type: string
Required: true - options
- ttl: Set a custom ttl for a cache item
Type: number
Default: globalttl
- ttl: Set a custom ttl for a cache item
- key: the key for the cache item
- get(key): get a cache item
- key: the key for the cache item
Type: string
Required: true
- key: the key for the cache item
- unset(key): remove an item from the cache
- key: the key for the cache item
Type: string
Required: true
- key: the key for the cache item
- hasKey(key): check if item with key exist in cache
- key: the key for the cache item
Type: string
Required: true
- key: the key for the cache item