@glenstack/cf-workers-function-memoizer
v1.0.1
Published
A wrapper which utilizes Cloudflare Workers KV to memoize a function
Downloads
8
Readme
Cloudflare Workers Function Memoizer
A wrapper which utilizes Cloudflare Workers KV to memoize a function.
Installation
npm install --save @glenstack/cf-workers-function-memoizer
Usage
import { makeMemoizer } from "@glenstack/cf-workers-function-memoizer";
const memoize = makeMemoizer(CACHE_KV_NAMESPACE);
let anExpensiveFunction = async (anArgument: string) => {
// ...
return someResult;
};
anExpensiveFunction = memoize(
anExpensiveFunction,
{
keyGenerator: (anArgument) => `anExpensiveFunction:${anArgument}`,
resultTransformer: JSON.stringify,
type: "json",
},
{
expirationTtl: 60 * 60,
}
);
// anExpensiveFunction is then ready to call with argument e.g. "hello"
(async () => {
// First time, it'll execute and then cache the `JSON.stringify`-d result with `anExpensiveFunction:hello`. The cached value is set to expire in 60 minutes.
let result = await anExpensiveFunction("hello");
// Subsequent calls will first look up the CACHE_KV_NAMESPACE and return the result if it is found, parsing as "json".
result = await anExpensiveFunction("hello");
// One hour later...
// Once the cached result is evicted, anExpensiveFunction will be re-run, and the result re-cached.
result = await anExpensiveFunction("hello");
})();
makeMemoizer
takes one parameter:
- The KV Namespace to be used as the cache.
It returns a function which, in turn, takes a three parameters:
The expensive async function to be memoized
Optionally, an object with the optional parameters:
keyGenerator
: A function which takes the same arguments as the memoized function, and returns a string to be used as the key in the cache KV namespace. By default, it creates a string formatted like:functionName:arg0,arg1,arg2...
Where
functionName
is the name of the memoized function and theargX
's are the arguments passed to it. Note: Function names often get minified by bundlers such as webpack, so you should strongly consider defining your ownkeyGenerator
function.resultTransformer
: A function which converts the memoized function's return value to a storable value in the KV namespace. Defaults toJSON.stringify
.type
: One of the supported types to parse KV values (the inverse ofresultTransformer
). Defaults to 'json'.
Optionally, an object of options to pass to KV when setting the value e.g. expiration times or metadata.
Finally, this can then be called in the same manner as the memoized function.