1.0.9 • Published 4 years ago
@fell/stash v1.0.9
stash
🗃 A nicer in-memory data cache library built with typescript.
this project is in very early beta, persistent data is yet to come, along with a better storage alternative.
🚀 Installation
npm
npm i @fell/stash
yarn
yarn add @fell/stash
✨ Include
typescript
import * as stash from '@fell/stash';
// with esModuleInterop
import stash from '@fell/stash';
javascript
const stash = require('@fell/stash');
🌴 Utils
use the logger to see what's being done.
stash.log();
// .... code below
wherever you execute stash.log(), code below will be logged.
set and get a stash cache key
set also takes in an expiry time, and expiry type
stash.set('name', 'ryan');
const name = stash.get('name');
console.log(name); // ryan
delete a stash cache key
const deleted = stash.del('name');
console.log(deleted); // true
returns true when a key is found and deleted, otherwise false
wrap a stash cache key to automatically update return cached value if N milliseconds passes, with a data request function.
proper use case
// function to get user data from a third party api
async function getUser(user) {
return stash.wrap(
`user_${user}`, // key
async () => {
// data request function
const { data } = await axios.get(`https://api/user/${user}`);
return data;
},
10 * 60 * 1000 // 10 minutes
);
}
const david = await getUser('david');
// wrap fetches data,
// caches the value
console.log(david);
const david_again = await getUser('david');
// wrap notices cached value,
// and N milliseconds hasn't passed yet
console.log(david);
setTimeout(() => {
const david_new = await getUser('david');
// wrap notices N milliseconds passed,
// fetches new data,
// updates cache
console.log(david);
}, 10 * 60 * 1000);
note: using the get() util instead of wrap() on a wrapped key, will always return the cached value, and never update the actual value.
get all stash cache keys currently in memory.
const all = stash.all();
console.log(all);
// an array of key strings