UNPKG

foxts

Version:

Opinionated collection of common TypeScript utils by @SukkaW

61 lines (59 loc) 3.02 kB
interface MemoizeStorageProvider { has(key: string): boolean | Promise<boolean>; get(key: string): string | undefined | PromiseLike<string | undefined>; set(key: string, value: string, ttl: number): void | Promise<void>; updateTtl?: (key: string, ttl: number) => void | Promise<void>; delete(key: string): void | Promise<void>; } interface CreateMemoizeOptions { /** * When set to true, the memoize will always try run the function first. * If promise resolved, it will update the cache. * If promise rejected, it will try to get the value from cache, and return * the cached value. If the cache is not available, it will throw the error. */ onlyUseCachedIfFail?: boolean; resetTtlOnHit?: boolean; defaultTtl?: number; onCacheUpdate?: (key: string, { humanReadableName }: { humanReadableName: string; isUseCachedIfFail: boolean; }) => void; onCacheMiss?: (key: string, { humanReadableName }: { humanReadableName: string; isUseCachedIfFail: boolean; }) => void; onCacheHit?: (key: string, { humanReadableName }: { humanReadableName: string; isUseCachedIfFail: boolean; }) => void; /** recommendation: import('hash-wasm').xxhash64 */ keyHasher?: (key: string) => Promise<string> | string; /** recommendation: import('devalue').stringify */ argHasher: (args: any[]) => Promise<string> | string; } type SerializableValue = number | string | boolean | bigint | Date | RegExp | Set<SerializableValue> | SerializableValue[] | null | undefined | Map<SerializableValue, SerializableValue> | SerializableObject | /** TypedArray */ Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | ArrayBuffer; interface SerializableObject { [key: string]: SerializableValue; } interface MemoizeBaseOptions { /** * The time to live of the cache in milliseconds. */ ttl?: number | null; temporaryBypass?: boolean; } interface MemoizeOptionsWithCustomSerializer<T> extends MemoizeBaseOptions { serializer: (value: T) => string; deserializer: (cached: string) => T; } type MemoizeOptions<T> = T extends string ? MemoizeBaseOptions : MemoizeOptionsWithCustomSerializer<T>; /** * A factory function that returns a memoize function. * * Unlike common memoize function out there, this serialize the parameters and returned value * for easy storing with file system, SQLite, Redis, etc. */ declare function createMemoize(storage: MemoizeStorageProvider, { onlyUseCachedIfFail, resetTtlOnHit, defaultTtl, onCacheUpdate, onCacheMiss, onCacheHit, keyHasher, argHasher }: CreateMemoizeOptions): <Args extends SerializableValue[], R>(fn: (...args: Args) => R | Promise<R>, opt?: MemoizeOptions<R>) => (...args: Args) => Promise<R>; export { createMemoize }; export type { CreateMemoizeOptions, MemoizeOptions, MemoizeStorageProvider, SerializableValue };