pinia-cache
Version:
Cache dispatched actions in memory and prevent repeated requests and heavy actions.
67 lines (64 loc) • 2.5 kB
TypeScript
import { Store, StateTree, _GettersTree, StoreDefinition, PiniaPluginContext } from 'pinia';
declare type CacheOptions = {
timeout?: number;
};
declare type Payload = unknown | Record<string, unknown>;
declare module 'pinia' {
interface PiniaCustomProperties {
cache: Cache;
}
interface DefineStoreOptionsBase<S, Store> {
cache?: CacheOptions;
}
}
declare type CacheRecord = {
expiresIn: number;
value: Promise<unknown>;
};
declare class Cache {
private _state;
private readonly _store;
private readonly _options;
constructor(store: Store, options: CacheOptions);
/**
* Resolve timeout from parameters and plugin options.
*/
private resolveTimeout;
/**
* Dispatch an action and set it on cache.
* @param {String} action
* @param {?any} payload
* @param {?any} options
* @returns {Promise<any>}
*/
dispatch(action: string, payload?: Payload, options?: CacheOptions): any;
/**
* Check if an action dispatch is on cache.
* @param {String} action
* @param {?any} payload
* * @returns {boolean}
*/
has(action: string, payload?: Payload): boolean;
/**
* Clear cache. Returns `true` if cache was cleared and `false` otherwise.
* If using the type parameter, only actions with the specified type are
* deleted from cache and the number of deleted keys is returned.
*/
clear(action?: string): boolean;
/**
* Delete an action dispatch from cache. Returns `true` if it was deleted
* and `false` otherwise.
*/
delete(action: string, payload?: Payload): boolean;
state(): Map<string, CacheRecord>;
}
declare type MapCacheActionsReturn<A> = {
[key in keyof A]: A[key];
};
declare type MapCacheActionsObjectReturn<A, T extends Record<string, keyof A>> = {
[key in keyof T]: A[T[key]];
};
declare function mapCacheActions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, KeyMapper extends Record<string, keyof A>>(useStore: StoreDefinition<Id, S, G, A>, keysOrMapper: KeyMapper): MapCacheActionsObjectReturn<A, KeyMapper>;
declare function mapCacheActions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A>(useStore: StoreDefinition<Id, S, G, A>, keys: Array<keyof A>): MapCacheActionsReturn<A>;
declare function piniaCachePlugin(context: PiniaPluginContext): void;
export { MapCacheActionsObjectReturn, MapCacheActionsReturn, mapCacheActions, piniaCachePlugin };