@pinia/plugin-debounce
Version:
Debounce any action in your pinia 🍍 store!
1 lines • 3.04 kB
Source Map (JSON)
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { PiniaPluginContext } from 'pinia'\n\n/**\n * Accepted interface for the debounce function passed to `PiniaDebounce`.\n */\nexport interface Debounce {\n (fn: (...args: any[]) => any, time: number): any\n}\n\n/**\n * Adds a `debounce` option to your store to debounce any action. The `debounce`\n * method can be lodash.debounce, ts-debounce, or any other debounce method.\n *\n * @example\n *\n * ```ts\n * import { debounce } from 'ts-debounce'\n *\n * // Pass the plugin to your application's pinia plugin\n * pinia.use(PiniaDebounce(debounce))\n * ```\n *\n * @param debounce - debounce method to be invoked\n */\nexport const PiniaDebounce =\n (debounce: Debounce) =>\n ({ options, store }: PiniaPluginContext) => {\n const { debounce: debounceOptions } = options\n if (debounceOptions) {\n return Object.keys(debounceOptions).reduce(\n (debouncedActions, action) => {\n const args = [store[action]].concat(debounceOptions[action])\n debouncedActions[action] = debounce.apply(\n null,\n // @ts-expect-error: wrong array type\n args\n )\n return debouncedActions\n },\n {} as Record<string, (...args: any[]) => any>\n )\n }\n }\n\ndeclare module 'pinia' {\n export interface DefineStoreOptionsBase<S, Store> {\n /**\n * Debounce any action by a specified amount of time in ms.\n *\n * @example\n *\n * ```js\n * defineStore('id', {\n * actions: { someSearch() {}},\n * debounce: {\n * // debounce all `someSearch` calls by 300ms\n * someSearch: 300\n * }\n * })\n * ```\n */\n debounce?: Partial<\n Record<\n keyof StoreActions<Store>,\n | number\n | (Config extends Record<'Debounce', infer DebounceFn>\n ? _ParamsAfterNumber<DebounceFn>\n : [number, ...any[]])\n >\n >\n }\n}\n\nexport type _ParamsAfterNumber<F> = F extends (\n fn: (...args: any[]) => any,\n time: number,\n ...rest: infer Rest\n) => any\n ? [number, ...Rest]\n : [number, ...any[]]\n\n/**\n * Allows you to provide a type for your debounce function so you can pass extra arguments to it in a type safe way.\n *\n * @example\n *\n * ```ts\n * // Add this to your main.ts or any other ts file\n * import { debounce } from 'ts-debounce'\n * declare module '@pinia/plugin-debounce' {\n * export interface Config {\n * Debounce: typeof debounce\n * }\n * }\n * ```\n */\nexport interface Config {\n // Debounce: any\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBO,IAAM,gBACX,CAAC,aACD,CAAC,EAAE,SAAS,MAAM,MAA0B;AAC1C,QAAM,EAAE,UAAU,gBAAgB,IAAI;AACtC,MAAI,iBAAiB;AACnB,WAAO,OAAO,KAAK,eAAe,EAAE;AAAA,MAClC,CAAC,kBAAkB,WAAW;AAC5B,cAAM,OAAO,CAAC,MAAM,MAAM,CAAC,EAAE,OAAO,gBAAgB,MAAM,CAAC;AAC3D,yBAAiB,MAAM,IAAI,SAAS;AAAA,UAClC;AAAA;AAAA,UAEA;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}