@spoosh/plugin-prefetch 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 +21 -0
- package/README.md +80 -0
- package/dist/index.d.mts +71 -0
- package/dist/index.d.ts +71 -0
- package/dist/index.js +179 -0
- package/dist/index.mjs +161 -0
- package/package.json +49 -0
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,80 @@
|
|
|
1
|
+
# @spoosh/plugin-prefetch
|
|
2
|
+
|
|
3
|
+
Prefetch plugin for Spoosh - preload data before it's needed.
|
|
4
|
+
|
|
5
|
+
**[Documentation](https://spoosh.dev/docs/plugins/prefetch)** · **Requirements:** TypeScript >= 5.0 · **Peer Dependencies:** `@spoosh/core`
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @spoosh/plugin-prefetch
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { prefetchPlugin } from "@spoosh/plugin-prefetch";
|
|
17
|
+
|
|
18
|
+
// Setup - prefetch is returned from createReactSpoosh
|
|
19
|
+
const plugins = [prefetchPlugin(), cachePlugin(), retryPlugin()];
|
|
20
|
+
const spoosh = createSpoosh<ApiSchema, Error, typeof plugins>({ baseUrl: "/api", plugins });
|
|
21
|
+
const { useRead, useWrite, prefetch } = createReactSpoosh(spoosh);
|
|
22
|
+
|
|
23
|
+
// Basic prefetch
|
|
24
|
+
await prefetch((api) => api.posts.$get());
|
|
25
|
+
|
|
26
|
+
// Prefetch with query options
|
|
27
|
+
await prefetch((api) => api.posts.$get({ query: { page: 1, limit: 10 } }));
|
|
28
|
+
|
|
29
|
+
// Prefetch with plugin options (staleTime, retries, etc.)
|
|
30
|
+
await prefetch(
|
|
31
|
+
(api) => api.users[userId].$get(),
|
|
32
|
+
{
|
|
33
|
+
staleTime: 60000,
|
|
34
|
+
retries: 3,
|
|
35
|
+
}
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
// Prefetch on hover
|
|
39
|
+
<Link
|
|
40
|
+
href="/posts/1"
|
|
41
|
+
onMouseEnter={() => prefetch((api) => api.posts[1].$get())}
|
|
42
|
+
>
|
|
43
|
+
View Post
|
|
44
|
+
</Link>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Options
|
|
48
|
+
|
|
49
|
+
### Plugin Config
|
|
50
|
+
|
|
51
|
+
| Option | Type | Default | Description |
|
|
52
|
+
| ---------------- | -------- | ------- | ----------------------------------------------------------------- |
|
|
53
|
+
| `staleTime` | `number` | - | Default stale time for prefetched data (ms) |
|
|
54
|
+
| `timeout` | `number` | `30000` | Timeout to auto-clear stale promises (ms). Prevents memory leaks. |
|
|
55
|
+
|
|
56
|
+
### Prefetch Options
|
|
57
|
+
|
|
58
|
+
The second argument to `prefetch()` accepts any plugin options (staleTime, retries, dedupe, etc.) plus:
|
|
59
|
+
|
|
60
|
+
| Option | Type | Description |
|
|
61
|
+
| ---------------- | ---------- | ------------------------- |
|
|
62
|
+
| `tags` | `string[]` | Custom cache tags |
|
|
63
|
+
| `additionalTags` | `string[]` | Additional tags to append |
|
|
64
|
+
|
|
65
|
+
## Features
|
|
66
|
+
|
|
67
|
+
### In-Flight Deduplication (Built-in)
|
|
68
|
+
|
|
69
|
+
Multiple calls to prefetch the same data will return the same promise, avoiding duplicate requests. This is built into the prefetch plugin - no deduplication plugin required.
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
// These will only make ONE network request
|
|
73
|
+
prefetch((api) => api.posts.$get());
|
|
74
|
+
prefetch((api) => api.posts.$get());
|
|
75
|
+
prefetch((api) => api.posts.$get());
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Memory Leak Prevention
|
|
79
|
+
|
|
80
|
+
Prefetch automatically clears promise references after completion or after `promiseTimeout` (default 30s). This prevents memory leaks from requests that never settle.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { QuerySchemaHelper, SpooshResponse, TagOptions, SpooshPlugin } from '@spoosh/core';
|
|
2
|
+
|
|
3
|
+
interface PrefetchPluginConfig {
|
|
4
|
+
/** Default stale time for prefetched data in milliseconds */
|
|
5
|
+
staleTime?: number;
|
|
6
|
+
/**
|
|
7
|
+
* Timeout in milliseconds after which stale promises are automatically cleared.
|
|
8
|
+
* Prevents memory leaks from requests that never settle.
|
|
9
|
+
* @default 30000 (30 seconds)
|
|
10
|
+
*/
|
|
11
|
+
timeout?: number;
|
|
12
|
+
}
|
|
13
|
+
interface PrefetchOptions extends TagOptions {
|
|
14
|
+
/** Additional plugin options (staleTime, retries, dedupe, etc.) */
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
type PrefetchCallbackFn<TSchema> = (api: QuerySchemaHelper<TSchema>) => Promise<SpooshResponse<unknown, unknown>>;
|
|
18
|
+
type PrefetchFn<TSchema, TPluginOptions = object> = <TData = unknown, TError = unknown>(selector: PrefetchCallbackFn<TSchema>, options?: PrefetchOptions & TPluginOptions) => Promise<SpooshResponse<TData, TError>>;
|
|
19
|
+
interface PrefetchInstanceApi {
|
|
20
|
+
prefetch: PrefetchFn<unknown>;
|
|
21
|
+
}
|
|
22
|
+
declare module "@spoosh/core" {
|
|
23
|
+
interface InstanceApiResolvers<TSchema> {
|
|
24
|
+
prefetch: PrefetchFn<TSchema>;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Provides prefetching capabilities to load data before it's needed.
|
|
30
|
+
*
|
|
31
|
+
* The prefetch function runs through the full plugin middleware chain,
|
|
32
|
+
* so features like caching, retry, and deduplication work automatically.
|
|
33
|
+
*
|
|
34
|
+
* @param config - Configuration options (reserved for future use)
|
|
35
|
+
*
|
|
36
|
+
* @see {@link https://spoosh.dev/docs/plugins/prefetch | Prefetch Plugin Documentation}
|
|
37
|
+
*
|
|
38
|
+
* @returns Prefetch plugin instance
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* // Setup
|
|
43
|
+
* const plugins = [prefetchPlugin(), cachePlugin(), retryPlugin()];
|
|
44
|
+
* const { prefetch } = createReactSpoosh(spoosh);
|
|
45
|
+
*
|
|
46
|
+
* // Basic prefetch
|
|
47
|
+
* await prefetch((api) => api.posts.$get());
|
|
48
|
+
*
|
|
49
|
+
* // Prefetch with query options
|
|
50
|
+
* await prefetch((api) => api.posts.$get({ query: { page: 1, limit: 10 } }));
|
|
51
|
+
*
|
|
52
|
+
* // Prefetch with plugin options (staleTime, retries, etc.)
|
|
53
|
+
* await prefetch((api) => api.users[userId].$get(), {
|
|
54
|
+
* staleTime: 60000,
|
|
55
|
+
* retries: 3,
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* // Prefetch on hover
|
|
59
|
+
* <Link
|
|
60
|
+
* href="/posts/1"
|
|
61
|
+
* onMouseEnter={() => prefetch((api) => api.posts[1].$get())}
|
|
62
|
+
* >
|
|
63
|
+
* View Post
|
|
64
|
+
* </Link>
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
declare function prefetchPlugin(config?: PrefetchPluginConfig): SpooshPlugin<{
|
|
68
|
+
instanceApi: PrefetchInstanceApi;
|
|
69
|
+
}>;
|
|
70
|
+
|
|
71
|
+
export { type PrefetchFn, type PrefetchInstanceApi, type PrefetchOptions, type PrefetchPluginConfig, prefetchPlugin };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { QuerySchemaHelper, SpooshResponse, TagOptions, SpooshPlugin } from '@spoosh/core';
|
|
2
|
+
|
|
3
|
+
interface PrefetchPluginConfig {
|
|
4
|
+
/** Default stale time for prefetched data in milliseconds */
|
|
5
|
+
staleTime?: number;
|
|
6
|
+
/**
|
|
7
|
+
* Timeout in milliseconds after which stale promises are automatically cleared.
|
|
8
|
+
* Prevents memory leaks from requests that never settle.
|
|
9
|
+
* @default 30000 (30 seconds)
|
|
10
|
+
*/
|
|
11
|
+
timeout?: number;
|
|
12
|
+
}
|
|
13
|
+
interface PrefetchOptions extends TagOptions {
|
|
14
|
+
/** Additional plugin options (staleTime, retries, dedupe, etc.) */
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
type PrefetchCallbackFn<TSchema> = (api: QuerySchemaHelper<TSchema>) => Promise<SpooshResponse<unknown, unknown>>;
|
|
18
|
+
type PrefetchFn<TSchema, TPluginOptions = object> = <TData = unknown, TError = unknown>(selector: PrefetchCallbackFn<TSchema>, options?: PrefetchOptions & TPluginOptions) => Promise<SpooshResponse<TData, TError>>;
|
|
19
|
+
interface PrefetchInstanceApi {
|
|
20
|
+
prefetch: PrefetchFn<unknown>;
|
|
21
|
+
}
|
|
22
|
+
declare module "@spoosh/core" {
|
|
23
|
+
interface InstanceApiResolvers<TSchema> {
|
|
24
|
+
prefetch: PrefetchFn<TSchema>;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Provides prefetching capabilities to load data before it's needed.
|
|
30
|
+
*
|
|
31
|
+
* The prefetch function runs through the full plugin middleware chain,
|
|
32
|
+
* so features like caching, retry, and deduplication work automatically.
|
|
33
|
+
*
|
|
34
|
+
* @param config - Configuration options (reserved for future use)
|
|
35
|
+
*
|
|
36
|
+
* @see {@link https://spoosh.dev/docs/plugins/prefetch | Prefetch Plugin Documentation}
|
|
37
|
+
*
|
|
38
|
+
* @returns Prefetch plugin instance
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* // Setup
|
|
43
|
+
* const plugins = [prefetchPlugin(), cachePlugin(), retryPlugin()];
|
|
44
|
+
* const { prefetch } = createReactSpoosh(spoosh);
|
|
45
|
+
*
|
|
46
|
+
* // Basic prefetch
|
|
47
|
+
* await prefetch((api) => api.posts.$get());
|
|
48
|
+
*
|
|
49
|
+
* // Prefetch with query options
|
|
50
|
+
* await prefetch((api) => api.posts.$get({ query: { page: 1, limit: 10 } }));
|
|
51
|
+
*
|
|
52
|
+
* // Prefetch with plugin options (staleTime, retries, etc.)
|
|
53
|
+
* await prefetch((api) => api.users[userId].$get(), {
|
|
54
|
+
* staleTime: 60000,
|
|
55
|
+
* retries: 3,
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* // Prefetch on hover
|
|
59
|
+
* <Link
|
|
60
|
+
* href="/posts/1"
|
|
61
|
+
* onMouseEnter={() => prefetch((api) => api.posts[1].$get())}
|
|
62
|
+
* >
|
|
63
|
+
* View Post
|
|
64
|
+
* </Link>
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
declare function prefetchPlugin(config?: PrefetchPluginConfig): SpooshPlugin<{
|
|
68
|
+
instanceApi: PrefetchInstanceApi;
|
|
69
|
+
}>;
|
|
70
|
+
|
|
71
|
+
export { type PrefetchFn, type PrefetchInstanceApi, type PrefetchOptions, type PrefetchPluginConfig, prefetchPlugin };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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
|
+
prefetchPlugin: () => prefetchPlugin
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(src_exports);
|
|
26
|
+
|
|
27
|
+
// src/plugin.ts
|
|
28
|
+
var import_core = require("@spoosh/core");
|
|
29
|
+
|
|
30
|
+
// src/promise-cache.ts
|
|
31
|
+
var DEFAULT_PROMISE_TIMEOUT = 3e4;
|
|
32
|
+
function storePromiseInCache(promise, options) {
|
|
33
|
+
const { stateManager, queryKey, timeout = DEFAULT_PROMISE_TIMEOUT } = options;
|
|
34
|
+
let promiseCleared = false;
|
|
35
|
+
const clearPromise = () => {
|
|
36
|
+
if (promiseCleared) return;
|
|
37
|
+
promiseCleared = true;
|
|
38
|
+
stateManager.setPendingPromise(queryKey, void 0);
|
|
39
|
+
};
|
|
40
|
+
stateManager.setPendingPromise(queryKey, promise);
|
|
41
|
+
const timeoutId = setTimeout(() => {
|
|
42
|
+
clearPromise();
|
|
43
|
+
}, timeout);
|
|
44
|
+
promise.finally(() => {
|
|
45
|
+
clearTimeout(timeoutId);
|
|
46
|
+
clearPromise();
|
|
47
|
+
});
|
|
48
|
+
return { clearPromise };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/plugin.ts
|
|
52
|
+
function prefetchPlugin(config = {}) {
|
|
53
|
+
const { timeout } = config;
|
|
54
|
+
return {
|
|
55
|
+
name: "spoosh:prefetch",
|
|
56
|
+
operations: [],
|
|
57
|
+
instanceApi(context) {
|
|
58
|
+
const { api, stateManager, eventEmitter, pluginExecutor } = context;
|
|
59
|
+
const prefetch = async (selector, options = {}) => {
|
|
60
|
+
const { tags, additionalTags } = options;
|
|
61
|
+
let callPath = [];
|
|
62
|
+
let callMethod = "";
|
|
63
|
+
let callOptions = void 0;
|
|
64
|
+
const selectorProxy = (0, import_core.createSelectorProxy)((result) => {
|
|
65
|
+
if (result.call) {
|
|
66
|
+
callPath = result.call.path;
|
|
67
|
+
callMethod = result.call.method;
|
|
68
|
+
callOptions = result.call.options;
|
|
69
|
+
} else if (result.selector) {
|
|
70
|
+
callPath = result.selector.path;
|
|
71
|
+
callMethod = result.selector.method;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
selector(selectorProxy);
|
|
75
|
+
if (!callMethod) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
"prefetch requires selecting a $get method. Example: prefetch((api) => api.posts.$get())"
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const resolvedPath = (0, import_core.resolvePath)(callPath, void 0);
|
|
81
|
+
const resolvedTags = (0, import_core.resolveTags)(
|
|
82
|
+
{ tags, additionalTags },
|
|
83
|
+
resolvedPath
|
|
84
|
+
);
|
|
85
|
+
const queryKey = stateManager.createQueryKey({
|
|
86
|
+
path: callPath,
|
|
87
|
+
method: callMethod,
|
|
88
|
+
options: callOptions
|
|
89
|
+
});
|
|
90
|
+
const initialState = (0, import_core.createInitialState)();
|
|
91
|
+
const abortController = new AbortController();
|
|
92
|
+
const pluginContext = pluginExecutor.createContext({
|
|
93
|
+
operationType: "read",
|
|
94
|
+
path: callPath,
|
|
95
|
+
method: callMethod,
|
|
96
|
+
queryKey,
|
|
97
|
+
tags: resolvedTags,
|
|
98
|
+
requestTimestamp: Date.now(),
|
|
99
|
+
requestOptions: callOptions ?? {},
|
|
100
|
+
state: initialState,
|
|
101
|
+
metadata: /* @__PURE__ */ new Map(),
|
|
102
|
+
pluginOptions: options,
|
|
103
|
+
abort: () => abortController.abort(),
|
|
104
|
+
stateManager,
|
|
105
|
+
eventEmitter
|
|
106
|
+
});
|
|
107
|
+
const coreFetch = async () => {
|
|
108
|
+
pluginContext.requestOptions.signal = abortController.signal;
|
|
109
|
+
const updateState = (updater) => {
|
|
110
|
+
const cached = stateManager.getCache(queryKey);
|
|
111
|
+
if (cached) {
|
|
112
|
+
stateManager.setCache(queryKey, {
|
|
113
|
+
state: { ...cached.state, ...updater }
|
|
114
|
+
});
|
|
115
|
+
} else {
|
|
116
|
+
stateManager.setCache(queryKey, {
|
|
117
|
+
state: { ...initialState, ...updater },
|
|
118
|
+
tags: resolvedTags
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
try {
|
|
123
|
+
let current = api;
|
|
124
|
+
for (const segment of resolvedPath) {
|
|
125
|
+
current = current[segment];
|
|
126
|
+
}
|
|
127
|
+
const method = current[callMethod];
|
|
128
|
+
const mergedOptions = {
|
|
129
|
+
...callOptions,
|
|
130
|
+
...pluginContext.requestOptions
|
|
131
|
+
};
|
|
132
|
+
const response = await method(mergedOptions);
|
|
133
|
+
pluginContext.response = response;
|
|
134
|
+
if (response.data !== void 0 && !response.error) {
|
|
135
|
+
updateState({
|
|
136
|
+
data: response.data,
|
|
137
|
+
error: void 0,
|
|
138
|
+
timestamp: Date.now()
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return response;
|
|
142
|
+
} catch (err) {
|
|
143
|
+
if (abortController.signal.aborted) {
|
|
144
|
+
return {
|
|
145
|
+
status: 0,
|
|
146
|
+
data: void 0,
|
|
147
|
+
error: void 0,
|
|
148
|
+
aborted: true
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const errorResponse = {
|
|
152
|
+
status: 0,
|
|
153
|
+
error: err,
|
|
154
|
+
data: void 0
|
|
155
|
+
};
|
|
156
|
+
pluginContext.response = errorResponse;
|
|
157
|
+
return errorResponse;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const existingPromise = stateManager.getPendingPromise(queryKey);
|
|
161
|
+
if (existingPromise) {
|
|
162
|
+
return existingPromise;
|
|
163
|
+
}
|
|
164
|
+
const fetchPromise = pluginExecutor.executeMiddleware(
|
|
165
|
+
"read",
|
|
166
|
+
pluginContext,
|
|
167
|
+
coreFetch
|
|
168
|
+
);
|
|
169
|
+
storePromiseInCache(fetchPromise, {
|
|
170
|
+
stateManager,
|
|
171
|
+
queryKey,
|
|
172
|
+
timeout
|
|
173
|
+
});
|
|
174
|
+
return fetchPromise;
|
|
175
|
+
};
|
|
176
|
+
return { prefetch };
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// src/plugin.ts
|
|
2
|
+
import {
|
|
3
|
+
createSelectorProxy,
|
|
4
|
+
resolvePath,
|
|
5
|
+
resolveTags,
|
|
6
|
+
createInitialState
|
|
7
|
+
} from "@spoosh/core";
|
|
8
|
+
|
|
9
|
+
// src/promise-cache.ts
|
|
10
|
+
var DEFAULT_PROMISE_TIMEOUT = 3e4;
|
|
11
|
+
function storePromiseInCache(promise, options) {
|
|
12
|
+
const { stateManager, queryKey, timeout = DEFAULT_PROMISE_TIMEOUT } = options;
|
|
13
|
+
let promiseCleared = false;
|
|
14
|
+
const clearPromise = () => {
|
|
15
|
+
if (promiseCleared) return;
|
|
16
|
+
promiseCleared = true;
|
|
17
|
+
stateManager.setPendingPromise(queryKey, void 0);
|
|
18
|
+
};
|
|
19
|
+
stateManager.setPendingPromise(queryKey, promise);
|
|
20
|
+
const timeoutId = setTimeout(() => {
|
|
21
|
+
clearPromise();
|
|
22
|
+
}, timeout);
|
|
23
|
+
promise.finally(() => {
|
|
24
|
+
clearTimeout(timeoutId);
|
|
25
|
+
clearPromise();
|
|
26
|
+
});
|
|
27
|
+
return { clearPromise };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// src/plugin.ts
|
|
31
|
+
function prefetchPlugin(config = {}) {
|
|
32
|
+
const { timeout } = config;
|
|
33
|
+
return {
|
|
34
|
+
name: "spoosh:prefetch",
|
|
35
|
+
operations: [],
|
|
36
|
+
instanceApi(context) {
|
|
37
|
+
const { api, stateManager, eventEmitter, pluginExecutor } = context;
|
|
38
|
+
const prefetch = async (selector, options = {}) => {
|
|
39
|
+
const { tags, additionalTags } = options;
|
|
40
|
+
let callPath = [];
|
|
41
|
+
let callMethod = "";
|
|
42
|
+
let callOptions = void 0;
|
|
43
|
+
const selectorProxy = createSelectorProxy((result) => {
|
|
44
|
+
if (result.call) {
|
|
45
|
+
callPath = result.call.path;
|
|
46
|
+
callMethod = result.call.method;
|
|
47
|
+
callOptions = result.call.options;
|
|
48
|
+
} else if (result.selector) {
|
|
49
|
+
callPath = result.selector.path;
|
|
50
|
+
callMethod = result.selector.method;
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
selector(selectorProxy);
|
|
54
|
+
if (!callMethod) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
"prefetch requires selecting a $get method. Example: prefetch((api) => api.posts.$get())"
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
const resolvedPath = resolvePath(callPath, void 0);
|
|
60
|
+
const resolvedTags = resolveTags(
|
|
61
|
+
{ tags, additionalTags },
|
|
62
|
+
resolvedPath
|
|
63
|
+
);
|
|
64
|
+
const queryKey = stateManager.createQueryKey({
|
|
65
|
+
path: callPath,
|
|
66
|
+
method: callMethod,
|
|
67
|
+
options: callOptions
|
|
68
|
+
});
|
|
69
|
+
const initialState = createInitialState();
|
|
70
|
+
const abortController = new AbortController();
|
|
71
|
+
const pluginContext = pluginExecutor.createContext({
|
|
72
|
+
operationType: "read",
|
|
73
|
+
path: callPath,
|
|
74
|
+
method: callMethod,
|
|
75
|
+
queryKey,
|
|
76
|
+
tags: resolvedTags,
|
|
77
|
+
requestTimestamp: Date.now(),
|
|
78
|
+
requestOptions: callOptions ?? {},
|
|
79
|
+
state: initialState,
|
|
80
|
+
metadata: /* @__PURE__ */ new Map(),
|
|
81
|
+
pluginOptions: options,
|
|
82
|
+
abort: () => abortController.abort(),
|
|
83
|
+
stateManager,
|
|
84
|
+
eventEmitter
|
|
85
|
+
});
|
|
86
|
+
const coreFetch = async () => {
|
|
87
|
+
pluginContext.requestOptions.signal = abortController.signal;
|
|
88
|
+
const updateState = (updater) => {
|
|
89
|
+
const cached = stateManager.getCache(queryKey);
|
|
90
|
+
if (cached) {
|
|
91
|
+
stateManager.setCache(queryKey, {
|
|
92
|
+
state: { ...cached.state, ...updater }
|
|
93
|
+
});
|
|
94
|
+
} else {
|
|
95
|
+
stateManager.setCache(queryKey, {
|
|
96
|
+
state: { ...initialState, ...updater },
|
|
97
|
+
tags: resolvedTags
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
let current = api;
|
|
103
|
+
for (const segment of resolvedPath) {
|
|
104
|
+
current = current[segment];
|
|
105
|
+
}
|
|
106
|
+
const method = current[callMethod];
|
|
107
|
+
const mergedOptions = {
|
|
108
|
+
...callOptions,
|
|
109
|
+
...pluginContext.requestOptions
|
|
110
|
+
};
|
|
111
|
+
const response = await method(mergedOptions);
|
|
112
|
+
pluginContext.response = response;
|
|
113
|
+
if (response.data !== void 0 && !response.error) {
|
|
114
|
+
updateState({
|
|
115
|
+
data: response.data,
|
|
116
|
+
error: void 0,
|
|
117
|
+
timestamp: Date.now()
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return response;
|
|
121
|
+
} catch (err) {
|
|
122
|
+
if (abortController.signal.aborted) {
|
|
123
|
+
return {
|
|
124
|
+
status: 0,
|
|
125
|
+
data: void 0,
|
|
126
|
+
error: void 0,
|
|
127
|
+
aborted: true
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const errorResponse = {
|
|
131
|
+
status: 0,
|
|
132
|
+
error: err,
|
|
133
|
+
data: void 0
|
|
134
|
+
};
|
|
135
|
+
pluginContext.response = errorResponse;
|
|
136
|
+
return errorResponse;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const existingPromise = stateManager.getPendingPromise(queryKey);
|
|
140
|
+
if (existingPromise) {
|
|
141
|
+
return existingPromise;
|
|
142
|
+
}
|
|
143
|
+
const fetchPromise = pluginExecutor.executeMiddleware(
|
|
144
|
+
"read",
|
|
145
|
+
pluginContext,
|
|
146
|
+
coreFetch
|
|
147
|
+
);
|
|
148
|
+
storePromiseInCache(fetchPromise, {
|
|
149
|
+
stateManager,
|
|
150
|
+
queryKey,
|
|
151
|
+
timeout
|
|
152
|
+
});
|
|
153
|
+
return fetchPromise;
|
|
154
|
+
};
|
|
155
|
+
return { prefetch };
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
export {
|
|
160
|
+
prefetchPlugin
|
|
161
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@spoosh/plugin-prefetch",
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "Prefetch plugin for Spoosh - preload data before it's needed",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nxnom/spoosh.git",
|
|
9
|
+
"directory": "packages/plugin-prefetch"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/nxnom/spoosh/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://spoosh.dev/docs/plugins/prefetch",
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"spoosh",
|
|
20
|
+
"plugin",
|
|
21
|
+
"prefetch",
|
|
22
|
+
"api-client",
|
|
23
|
+
"preload"
|
|
24
|
+
],
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"import": "./dist/index.mjs",
|
|
32
|
+
"require": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@spoosh/core": ">=0.1.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@spoosh/core": "0.1.0-beta.0",
|
|
40
|
+
"@spoosh/test-utils": "0.1.0-beta.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"dev": "tsup --watch",
|
|
44
|
+
"build": "tsup",
|
|
45
|
+
"typecheck": "tsc --noEmit",
|
|
46
|
+
"lint": "eslint src --max-warnings 0",
|
|
47
|
+
"format": "prettier --write 'src/**/*.ts'"
|
|
48
|
+
}
|
|
49
|
+
}
|