-
Notifications
You must be signed in to change notification settings - Fork 21
Cache
Charlie's utilities include a cache to speed up long-running tasks. The cache is key-based, so you can quickly retrieve the last result of a cached operation for up to a set lifetime. The cache has a maximum lifetime of 20 minutes to prevent memory leaks, so any configured caching over 20 minutes will fall back to just 20 minutes.
Argument | Description |
---|---|
key |
The key for this cache. Cache keys should be unique for the data being cached. |
lifetime |
How long to cache the results, in minutes. The maximum is 20 minutes. |
callback |
The function to call if there are no cached results, or the results are older than the specified lifetime. The callback should return a promise that resolves to the value to be cached. |
Returns
- A promise that resolves to the cached value if the cache is fresh, or resolves to the value from the callback if the cache is stale.
In this example, if it has been less than 10 minutes since the callback was
called, values
will resolve to the previous results. Otherwise, it will
resolve to the results of the fetch
call.
const { cache } = require("../utils");
const values = await cache("cached value", 10, async () => {
return fetch("https://get.values");
});
In this example, an independent cache will be created for each key
value
passed into getValues
. If it has been less than 10 minues since the callback
was called, the cache will immediately resolve the previous results. Otherwise,
it will resolve the results of the fetch
call.
// From a script...
const { cache } = require("../utils");
const getValues = (key) =>
cache(`cached values: ${key}`, 10, async () => {
return fetch(`https://get.values/${key}`);
});
Charlie developer documentation