Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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.
- Host: GitHub
- URL: https://github.com/nwaughachukwuma/sma-cache
- Owner: nwaughachukwuma
- Created: 2021-09-25T19:10:49.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-12-11T01:11:42.000Z (about 2 years ago)
- Last Synced: 2024-10-08T15:52:24.437Z (3 months ago)
- Language: TypeScript
- Size: 205 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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