UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

68 lines (67 loc) 2.67 kB
import type { AnyObject, UnixTimestamp } from '../types.js'; import { MISS } from '../types.js'; export type MemoSerializer = (args: any[]) => any; export declare const jsonMemoSerializer: MemoSerializer; export interface MemoCacheOptions { /** * If set (and if it's implemented by the driver) - will set expiry TTL for each key of the batch. * E.g EXAT in Redis. */ expireAt?: UnixTimestamp; } export interface MemoCache<KEY = any, VALUE = any> { has: (k: KEY) => boolean; /** * `get` return signature doesn't contain `undefined`, * because `undefined` is a valid VALUE to store in the Cache. * `undefined` does NOT mean cache miss. * Cache misses are checked by calling `has` method instead. */ get: (k: KEY) => VALUE; set: (k: KEY, v: VALUE, opt?: MemoCacheOptions) => void; /** * Clear is only called when `_getMemoCache().clear()` is called. * Otherwise the Cache is "persistent" (never cleared). */ clear: () => void; } export interface AsyncMemoCache<KEY = any, VALUE = any> { /** * MISS symbol indicates the ABSENCE of value in the Cache. * You can safely store `undefined` or `null` values in the Cache, * they will not be interpreted as a cache miss, because there is a special MISS symbol for that. */ get: (k: KEY) => Promise<VALUE | typeof MISS>; set: (k: KEY, v: VALUE, opt?: MemoCacheOptions) => Promise<void>; /** * Clear is only called when `_getAsyncMemo().clear()` is called. * Otherwise the Cache is "persistent" (never cleared). */ clear: () => Promise<void>; } export declare class MapMemoCache<KEY = any, VALUE = any> implements MemoCache<KEY, VALUE> { private m; has(k: KEY): boolean; get(k: KEY): VALUE; set(k: KEY, v: VALUE): void; clear(): void; } /** * Implementation of AsyncMemoCache backed by a synchronous Map. * Doesn't have a practical use except testing, * because the point of AsyncMemoCache is to have an **async** backed cache. */ export declare class MapAsyncMemoCache<KEY = any, VALUE = any> implements AsyncMemoCache<KEY, VALUE> { private delay; constructor(delay?: number); private m; get(k: KEY): Promise<VALUE | typeof MISS>; set(k: KEY, v: VALUE): Promise<void>; clear(): Promise<void>; } /** * Generic override of Typescript's built in legacy MethodDecorator, that * allows us to infer the parameters of the decorated method from the parameters * of a decorator. */ export type MethodDecorator<T> = (target: AnyObject, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | undefined;