import { asyncCacheFn } from 'async-cache-fn'
export const getData = asyncCacheFn(async (url) => {
const data = await fetch(url)
return await data.json()
})
const users = await getData('/users')
const posts = await getData('/posts')
// in other place, `/users` will only be requested once and the result will be cached.
const users2 = await getData('/users')
By default, we use lru-cache
with 1,000 capacity. To customize LRU cache, you can pass lru
option
export const fn = asyncCacheFn(
async (url) => {
// do something...
},
{
lru: { /* full lru-cache options */ }
}
)
Or you can set false
to completely disable LRU cache, which will use Map instead (be cautious with potential memory leak, you need to clear the cache manually).
export const fn = asyncCacheFn(
async (url) => {
// do something...
},
{
lru: false // disable
}
)
By default, we apply safe-stable-stringify
to the arguments as the key for caching.
You may provide a custom function to how the get been generated:
import { asyncCacheFn, stableStringify } from 'async-cache-fn'
export const multiply = asyncCacheFn(
async (n, m) => {
return n * m
},
{
// since the order of multiply is interchangeable,
// we sort it to improve the cache matching
getKey(args) {
return stableStringify(args.sort())
}
}
)
stringify()
fromsafe-stable-stringify
is re-exported asstableStringify()
You can have fine-grain control of the caching accessing utils on the cached function:
export const multiply = asyncCacheFn(async (n, m) => {
return n * m
})
multiply(2, 3)
multiply.has(2, 3) // true
multiply.has(4, 5) // false
await multiply.get(2, 3) // 6
// clear all cache
multiply.clear()
You can check the type definition for all utilities available.
TODO
Please check the check the type definition for now.
MIT License 2022 Anthony Fu