A better in-memory cache for Node and the browser
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Fix mocha tests not exiting Jan 9, 2019
.eslintrc.js Fix mocha tests not exiting Jan 9, 2019
.gitignore Initial commit Jan 9, 2019
.travis.yml Add badges and travis config Jan 9, 2019
README.md Update README.md Jan 11, 2019
package-lock.json Initial commit Jan 9, 2019
package.json Bump for readme update -> NPM Jan 11, 2019

README.md

Keshi

Keshi on NPM Keshi on TravisCI

Keshi is a better in-memory cache for Node and the browser.

const createCache = require('keshi')

or

import createCache from 'keshi'

Usage

const cache = createCache()

const user = await cache.resolve('user', () => fetch('https://myapi.com/user').then(r => json()), '30 mins')

What this will do:

  • Fetch the user from the API as it doesn't have it in cache.
  • If called again within 30 minutes it will return the cached user.
  • If called after 30 minutes it will fetch the user again and re-cache.

Cache the data you need

You should return only the data you need to keep the cache efficient. Here's a real world example of caching repository information from GitHub:

// In the browser
const fetchProjectMeta = (user, repo) => fetch(`https://api.github.com/repos/${user}/${repo}`)
  .then(r => r.json())
  .then(r => ({ name: r.full_name, description: r.description }));

// ...or in Node
const fetchProjectMeta = (user, repo) => got.get(`https://api.github.com/repos/${user}/${repo}`, { json: true })
  .then(r => ({ name: r.body.full_name, description: r.body.description }));

// And call it (for 1 hour it will return cached results).
const meta = await cache.resolve('myRepo', fetchProjectMeta('DominicTobias', 'keshi'), '1 hour');

Rate limited APIs (as above), saving bandwidth, dealing with poor client network speeds, returning server responses faster are some of the reasons you might consider caching requests.

Keshi will automatically keep memory low by cleaning up expired items.

API

resolve(key, [value], [expiresIn])

key → String → Required

value → Any → Optional

A function which resolves to a value, or simply a literal value.

expiresIn → Number | String | Function → Optional

A number in milliseconds or anything that ms accepts after which the value is considered expired. If no expiry is provided the item will never expire.

Can also be a function (async is allowed) which returns true if the item has expired or otherwise false. e.g.

// Expire 50% of the time.
const date = await cache.resolve('date', () => new Date(), () => Math.random() >= 0.5)

del(key)

Delete a cached item by key.

clear()

Clear all cached items.