with-simple-caching
Version:
A wrapper that makes it simple to add caching to any function
66 lines (65 loc) • 2.81 kB
TypeScript
import { UniDuration } from '@ehmpathy/uni-time';
import { NotUndefined } from 'type-fns';
import { SimpleSyncCache } from '../../domain/SimpleCache';
import { WithSimpleCachingCacheOption } from '../options/getCacheFromCacheOption';
import { KeySerializationMethod } from '../serde/defaults';
/**
* options to configure caching for use with-simple-caching
*/
export interface WithSimpleCachingOptions<
/**
* the logic we are caching the responses for
*/
L extends (...args: any) => any,
/**
* the type of cache being used
*/
C extends SimpleSyncCache<any>> {
cache: WithSimpleCachingCacheOption<Parameters<L>, C>;
serialize?: {
key?: KeySerializationMethod<Parameters<L>>;
value?: (output: ReturnType<L>) => NotUndefined<ReturnType<C['get']>>;
};
deserialize?: {
value?: (cached: NotUndefined<ReturnType<C['get']>>) => ReturnType<L>;
};
expiration?: UniDuration | null;
/**
* whether to bypass the cached for either the set or get operation
*/
bypass?: {
/**
* whether to bypass the cache for the get
*
* note
* - equivalent to the result not already being cached
*
* default
* - process.env.CACHE_BYPASS_GET ? process.env.CACHE_BYPASS_GET === 'true' : process.env.CACHE_BYPASS === 'true'
*/
get?: (input: Parameters<L>) => boolean;
/**
* whether to bypass the cache for the set
*
* note
* - keeps whatever the previously cached value was, while returning the new value
*
* default
* - process.env.CACHE_BYPASS_SET ? process.env.CACHE_BYPASS_SET === 'true' : process.env.CACHE_BYPASS === 'true'
*/
set?: (input: Parameters<L>) => boolean;
};
}
/**
* a wrapper which uses a synchronous cache to cache the result of the wrapped logic
*
* for example:
* ```ts
* const getApiResult = withSimpleCaching(({ name, number }) => axios.get(URL, { name, number }));
* const result1 = getApiResult({ name: 'casey', number: 821 }); // calls the api, puts promise of results into cache, returns that promise
* const result2 = getApiResult({ name: 'casey', number: 821 }); // returns the same promise from above, because it was found in cache - since same input as request above was used
* expect(result1).toBe(result2); // same exact object - the promise
* expect(await result1).toBe(await result2); // same exact object - the result of the promise
* ```
*/
export declare const withSimpleCaching: <L extends (...args: any[]) => any, C extends SimpleSyncCache<any>>(logic: L, { cache: cacheOption, serialize: { key: serializeKey, value: serializeValue, }, deserialize: { value: deserializeValue, }, expiration, bypass, }: WithSimpleCachingOptions<L, C>) => L;