Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/nwaughachukwuma/sma-cache

Cache any data-type within a given ttl, with automatic invalidation.
https://github.com/nwaughachukwuma/sma-cache

Last synced: about 1 month ago
JSON representation

Cache any data-type within a given ttl, with automatic invalidation.

Awesome Lists containing this project

README

        

# Sma-cache

A simple memory cache with automatic invalidation after TTL. Runs on the browser and node

## Installation

```shell
# npm
npm install sma-cache

# yarn
yarn add sma-cache

# pnpm
pnpm install sma-cache
```

## Usage

```js
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:

```js
// using a delay mechanism
delay(TTL);
cache.get(key); // => undefined
```

### Example

```js
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();
```

## API

### simpleCache(ttl)

Returns a `cache object` which exposes methods to interact with the cache

### ttl

Time in milliseconds before the item stored with `key: random-key` is invalidated

Type: number

Default: 6000

### Cache Object API

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: global `ttl`
- **get(key)**: get a cache item
- **key**: the key for the cache item

Type: string

Required: true
- **unset(key)**: remove an item from the cache
- **key**: the key for the cache item

Type: string

Required: true
- **hasKey(key)**: check if item with key exist in cache
- **key**: the key for the cache item

Type: string

Required: true