@spoosh/plugin-polling 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Spoosh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # @spoosh/plugin-polling
2
+
3
+ Automatic polling/refetching plugin for Spoosh.
4
+
5
+ **[Documentation](https://spoosh.dev/docs/plugins/polling)** · **Requirements:** TypeScript >= 5.0 · **Peer Dependencies:** `@spoosh/core`
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @spoosh/plugin-polling
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { pollingPlugin } from "@spoosh/plugin-polling";
17
+
18
+ const plugins = [pollingPlugin()];
19
+
20
+ // Static polling interval (5 seconds)
21
+ useRead((api) => api.posts.$get(), { pollingInterval: 5000 });
22
+
23
+ // Disable polling (Default behavior)
24
+ useRead((api) => api.posts.$get(), { pollingInterval: false });
25
+
26
+ // Dynamic polling interval based on data/error
27
+ useRead((api) => api.booking[123].$get(), {
28
+ pollingInterval: (data, error) => {
29
+ if (error) return 10000; // Slower polling on error
30
+ if (data?.status === "pending") return 1000; // Fast polling for pending
31
+ return 5000; // Normal polling
32
+ },
33
+ });
34
+ ```
35
+
36
+ ## Options
37
+
38
+ ### Per-Request Options
39
+
40
+ | Option | Type | Description |
41
+ | ----------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
42
+ | `pollingInterval` | `number \| false \| (data, error) => number \| false` | Polling interval in milliseconds, `false` to disable, or a function for dynamic intervals |
43
+
44
+ ## Dynamic Polling
45
+
46
+ The polling interval can be a function that receives the current data and error, allowing you to adjust the polling rate based on the response:
47
+
48
+ ```typescript
49
+ useRead((api) => api.jobs(":id").$get({ id: jobId }), {
50
+ pollingInterval: (data) => {
51
+ // Stop polling when job is complete
52
+ if (data?.status === "completed") return false;
53
+
54
+ // Poll faster while job is running
55
+ if (data?.status === "running") return 1000;
56
+
57
+ // Default interval
58
+ return 5000;
59
+ },
60
+ });
61
+ ```
@@ -0,0 +1,51 @@
1
+ import { SpooshPlugin } from '@spoosh/core';
2
+
3
+ type PollingIntervalValue = number | false;
4
+ type PollingIntervalFn<TData = unknown, TError = unknown> = (data: TData | undefined, error: TError | undefined) => PollingIntervalValue;
5
+ type PollingInterval<TData = unknown, TError = unknown> = PollingIntervalValue | PollingIntervalFn<TData, TError>;
6
+ interface PollingReadOptions {
7
+ /** Polling interval in milliseconds, `false` to disable, or a function for dynamic intervals. */
8
+ pollingInterval?: PollingInterval;
9
+ }
10
+ type PollingWriteOptions = object;
11
+ type PollingInfiniteReadOptions = object;
12
+ type PollingReadResult = object;
13
+ type PollingWriteResult = object;
14
+ declare module "@spoosh/core" {
15
+ interface PluginResolvers<TContext> {
16
+ pollingInterval: PollingInterval<TContext["data"], TContext["error"]> | undefined;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Enables automatic polling for queries at configurable intervals.
22
+ *
23
+ * Automatically refetches data at specified intervals to keep it fresh.
24
+ * Supports dynamic intervals based on current data or error state.
25
+ *
26
+ * @see {@link https://spoosh.dev/docs/plugins/polling | Polling Plugin Documentation}
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const plugins = [pollingPlugin()];
31
+ *
32
+ * // Poll every 5 seconds
33
+ * useRead((api) => api.posts.$get(), {
34
+ * pollingInterval: 5000,
35
+ * });
36
+ *
37
+ * // Dynamic interval based on data
38
+ * useRead((api) => api.posts.$get(), {
39
+ * pollingInterval: (data, error) => error ? 10000 : 5000,
40
+ * });
41
+ * ```
42
+ */
43
+ declare function pollingPlugin(): SpooshPlugin<{
44
+ readOptions: PollingReadOptions;
45
+ writeOptions: PollingWriteOptions;
46
+ infiniteReadOptions: PollingInfiniteReadOptions;
47
+ readResult: PollingReadResult;
48
+ writeResult: PollingWriteResult;
49
+ }>;
50
+
51
+ export { type PollingInfiniteReadOptions, type PollingInterval, type PollingIntervalFn, type PollingIntervalValue, type PollingReadOptions, type PollingReadResult, type PollingWriteOptions, type PollingWriteResult, pollingPlugin };
@@ -0,0 +1,51 @@
1
+ import { SpooshPlugin } from '@spoosh/core';
2
+
3
+ type PollingIntervalValue = number | false;
4
+ type PollingIntervalFn<TData = unknown, TError = unknown> = (data: TData | undefined, error: TError | undefined) => PollingIntervalValue;
5
+ type PollingInterval<TData = unknown, TError = unknown> = PollingIntervalValue | PollingIntervalFn<TData, TError>;
6
+ interface PollingReadOptions {
7
+ /** Polling interval in milliseconds, `false` to disable, or a function for dynamic intervals. */
8
+ pollingInterval?: PollingInterval;
9
+ }
10
+ type PollingWriteOptions = object;
11
+ type PollingInfiniteReadOptions = object;
12
+ type PollingReadResult = object;
13
+ type PollingWriteResult = object;
14
+ declare module "@spoosh/core" {
15
+ interface PluginResolvers<TContext> {
16
+ pollingInterval: PollingInterval<TContext["data"], TContext["error"]> | undefined;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Enables automatic polling for queries at configurable intervals.
22
+ *
23
+ * Automatically refetches data at specified intervals to keep it fresh.
24
+ * Supports dynamic intervals based on current data or error state.
25
+ *
26
+ * @see {@link https://spoosh.dev/docs/plugins/polling | Polling Plugin Documentation}
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const plugins = [pollingPlugin()];
31
+ *
32
+ * // Poll every 5 seconds
33
+ * useRead((api) => api.posts.$get(), {
34
+ * pollingInterval: 5000,
35
+ * });
36
+ *
37
+ * // Dynamic interval based on data
38
+ * useRead((api) => api.posts.$get(), {
39
+ * pollingInterval: (data, error) => error ? 10000 : 5000,
40
+ * });
41
+ * ```
42
+ */
43
+ declare function pollingPlugin(): SpooshPlugin<{
44
+ readOptions: PollingReadOptions;
45
+ writeOptions: PollingWriteOptions;
46
+ infiniteReadOptions: PollingInfiniteReadOptions;
47
+ readResult: PollingReadResult;
48
+ writeResult: PollingWriteResult;
49
+ }>;
50
+
51
+ export { type PollingInfiniteReadOptions, type PollingInterval, type PollingIntervalFn, type PollingIntervalValue, type PollingReadOptions, type PollingReadResult, type PollingWriteOptions, type PollingWriteResult, pollingPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ pollingPlugin: () => pollingPlugin
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+
27
+ // src/plugin.ts
28
+ function pollingPlugin() {
29
+ const timeouts = /* @__PURE__ */ new Map();
30
+ const clearPolling = (queryKey) => {
31
+ const timeout = timeouts.get(queryKey);
32
+ if (timeout) {
33
+ clearTimeout(timeout);
34
+ timeouts.delete(queryKey);
35
+ }
36
+ };
37
+ const scheduleNextPoll = (context) => {
38
+ const { queryKey, eventEmitter } = context;
39
+ const pluginOptions = context.pluginOptions;
40
+ const pollingInterval = pluginOptions?.pollingInterval;
41
+ if (!pollingInterval) return;
42
+ const cached = context.stateManager.getCache(queryKey);
43
+ const data = cached?.state.data;
44
+ const error = cached?.state.error;
45
+ const resolvedInterval = typeof pollingInterval === "function" ? pollingInterval(data, error) : pollingInterval;
46
+ if (resolvedInterval === false || resolvedInterval <= 0) return;
47
+ clearPolling(queryKey);
48
+ const timeout = setTimeout(() => {
49
+ timeouts.delete(queryKey);
50
+ eventEmitter.emit("refetch", {
51
+ queryKey,
52
+ reason: "polling"
53
+ });
54
+ }, resolvedInterval);
55
+ timeouts.set(queryKey, timeout);
56
+ };
57
+ return {
58
+ name: "spoosh:polling",
59
+ operations: ["read", "infiniteRead"],
60
+ onResponse(context) {
61
+ scheduleNextPoll(context);
62
+ },
63
+ lifecycle: {
64
+ onUpdate(context, previousContext) {
65
+ if (previousContext.queryKey !== context.queryKey) {
66
+ clearPolling(previousContext.queryKey);
67
+ }
68
+ const { queryKey } = context;
69
+ const pluginOptions = context.pluginOptions;
70
+ const pollingInterval = pluginOptions?.pollingInterval;
71
+ if (!pollingInterval) {
72
+ clearPolling(queryKey);
73
+ return;
74
+ }
75
+ const currentTimeout = timeouts.get(queryKey);
76
+ if (!currentTimeout) {
77
+ scheduleNextPoll(context);
78
+ }
79
+ },
80
+ onUnmount(context) {
81
+ clearPolling(context.queryKey);
82
+ }
83
+ }
84
+ };
85
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,62 @@
1
+ // src/plugin.ts
2
+ function pollingPlugin() {
3
+ const timeouts = /* @__PURE__ */ new Map();
4
+ const clearPolling = (queryKey) => {
5
+ const timeout = timeouts.get(queryKey);
6
+ if (timeout) {
7
+ clearTimeout(timeout);
8
+ timeouts.delete(queryKey);
9
+ }
10
+ };
11
+ const scheduleNextPoll = (context) => {
12
+ const { queryKey, eventEmitter } = context;
13
+ const pluginOptions = context.pluginOptions;
14
+ const pollingInterval = pluginOptions?.pollingInterval;
15
+ if (!pollingInterval) return;
16
+ const cached = context.stateManager.getCache(queryKey);
17
+ const data = cached?.state.data;
18
+ const error = cached?.state.error;
19
+ const resolvedInterval = typeof pollingInterval === "function" ? pollingInterval(data, error) : pollingInterval;
20
+ if (resolvedInterval === false || resolvedInterval <= 0) return;
21
+ clearPolling(queryKey);
22
+ const timeout = setTimeout(() => {
23
+ timeouts.delete(queryKey);
24
+ eventEmitter.emit("refetch", {
25
+ queryKey,
26
+ reason: "polling"
27
+ });
28
+ }, resolvedInterval);
29
+ timeouts.set(queryKey, timeout);
30
+ };
31
+ return {
32
+ name: "spoosh:polling",
33
+ operations: ["read", "infiniteRead"],
34
+ onResponse(context) {
35
+ scheduleNextPoll(context);
36
+ },
37
+ lifecycle: {
38
+ onUpdate(context, previousContext) {
39
+ if (previousContext.queryKey !== context.queryKey) {
40
+ clearPolling(previousContext.queryKey);
41
+ }
42
+ const { queryKey } = context;
43
+ const pluginOptions = context.pluginOptions;
44
+ const pollingInterval = pluginOptions?.pollingInterval;
45
+ if (!pollingInterval) {
46
+ clearPolling(queryKey);
47
+ return;
48
+ }
49
+ const currentTimeout = timeouts.get(queryKey);
50
+ if (!currentTimeout) {
51
+ scheduleNextPoll(context);
52
+ }
53
+ },
54
+ onUnmount(context) {
55
+ clearPolling(context.queryKey);
56
+ }
57
+ }
58
+ };
59
+ }
60
+ export {
61
+ pollingPlugin
62
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@spoosh/plugin-polling",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Automatic polling/refetching plugin for Spoosh",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nxnom/spoosh.git",
9
+ "directory": "packages/plugin-polling"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/nxnom/spoosh/issues"
13
+ },
14
+ "homepage": "https://spoosh.dev/docs/plugins/polling",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "spoosh",
20
+ "plugin",
21
+ "polling",
22
+ "interval",
23
+ "auto-refresh",
24
+ "api-client"
25
+ ],
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.mjs",
33
+ "require": "./dist/index.js"
34
+ }
35
+ },
36
+ "peerDependencies": {
37
+ "@spoosh/core": ">=0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@spoosh/core": "0.1.0-beta.0",
41
+ "@spoosh/test-utils": "0.1.0-beta.0"
42
+ },
43
+ "scripts": {
44
+ "dev": "tsup --watch",
45
+ "build": "tsup",
46
+ "typecheck": "tsc --noEmit",
47
+ "lint": "eslint src --max-warnings 0",
48
+ "format": "prettier --write 'src/**/*.ts'"
49
+ }
50
+ }