Keshi is a better in-memory cache for Node and the browser.
const createCache = require('keshi')
or
import createCache from 'keshi'
const cache = createCache()
const user = await cache.resolve('user', () => fetch('https://myapi.com/user'), '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.
You should return only the data you need to keep the cache efficient. Here's a real world Node example of caching repository information from GitHub:
const fetchProjectMeta = project => got.get(`https://api.github.com/repositories/${project.repo.id}`, {
json: true,
headers: {
Authorization: `token ${project.accessToken}`,
},
}).then(r => ({ name: r.body.full_name, description: r.body.description })); // Caching name and desc
async function resolveProjectMeta(project) {
try {
const meta = await cache.resolve(project.repo.id, fetchProjectMeta(project), '1 hour');
return { ...project, ...meta };
} catch (e) {
console.error(e);
return project;
}
}
Among other things caches are ideal when dealing with rate limited external APIs (and saving bandwidth), without the worries of persistant data.
Keshi will automatically keep memory low by cleaning up expired items.
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)
Delete a cached item by key.
Clear all cached items.