nuxt-custom-fetch 4.4.8 → 4.5.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 +25 -12
- package/dist/module.d.mts +3 -3
- package/dist/module.json +1 -1
- package/dist/module.mjs +3 -3
- package/dist/runtime/ajax.d.ts +6 -6
- package/dist/runtime/ajax.js +68 -43
- package/dist/runtime/type.d.ts +1 -1
- package/dist/runtime/utils.js +11 -9
- package/package.json +6 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 xjccc
|
|
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
CHANGED
|
@@ -14,7 +14,7 @@ Use `CustomFetch` when you specifically need an extra request layer on top of th
|
|
|
14
14
|
|
|
15
15
|
## Compatibility
|
|
16
16
|
|
|
17
|
-
- `v4`: Nuxt `>= 4.
|
|
17
|
+
- `v4`: Nuxt `>= 4.5.0`
|
|
18
18
|
- `v2`: Nuxt `3.0.0` to `3.16.x`
|
|
19
19
|
|
|
20
20
|
## Current Maintenance Summary
|
|
@@ -24,9 +24,10 @@ The current implementation is maintained around these guarantees:
|
|
|
24
24
|
- runtime behavior is aligned with Nuxt 4 async-data semantics where possible
|
|
25
25
|
- public method generics follow Nuxt `AsyncData` typing more closely
|
|
26
26
|
- reactive `key`, `baseURL`, `params`, `query`, `headers`, `body`, and `cache` values are resolved before each request
|
|
27
|
-
- generated keys include both `params` and `query`, which avoids stale client reuse when only one side changes
|
|
27
|
+
- generated keys are derived with Nuxt's `hashKey` (the same digest `useFetch` uses) and include both `params` and `query`, which avoids stale client reuse when only one side changes
|
|
28
28
|
- same-key client compatibility requests share one async-data bucket, so `dedupe: 'cancel'` can abort the previous pending request
|
|
29
29
|
- the client compatibility path mirrors Nuxt 4 async-data behavior: `pending` follows the `pendingWhenIdle` config, `refreshNuxtData()` (the `app:data:refresh` hook) re-runs fallback requests, `getCachedData` is honored and successful data is written back to `nuxtApp.payload.data`
|
|
30
|
+
- the client compatibility path honors Nuxt 4.5's `enabled` option (a reactive `enabled` turning `false` cancels the in-flight request) and cancels an in-flight request when its owning scope is disposed
|
|
30
31
|
- timeouts and external abort signals are merged into one request signal (via `AbortSignal.timeout`/`AbortSignal.any` semantics), key watchers are only created for reactive keys, and a key change re-runs the request when `immediate`, prior data, or an in-flight request is present
|
|
31
32
|
- Vitest runtime tests and TypeScript type tests cover the wrapper behavior
|
|
32
33
|
|
|
@@ -55,8 +56,8 @@ export const useCachedData = createUseAsyncData({
|
|
|
55
56
|
|
|
56
57
|
## How It Works
|
|
57
58
|
|
|
58
|
-
- In `setup
|
|
59
|
-
- After
|
|
59
|
+
- In `setup` (including client-side navigation), route middleware, plugins during hydration, and other setup-compatible contexts, `CustomFetch` delegates back to `useAsyncData`, so options such as `lazy`, `server`, and `enabled` follow Nuxt exactly.
|
|
60
|
+
- After hydration on the client, calls made outside component setup (event handlers, lifecycle hooks such as `onMounted`, watchers) fall back to a compatibility mode. This is the same condition under which Nuxt warns "Component is already mounted".
|
|
60
61
|
- The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
|
|
61
62
|
- The compatibility mode is not a full SSR payload or cache replacement.
|
|
62
63
|
- Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules.
|
|
@@ -162,12 +163,22 @@ export function getReactivePageList (page: Ref<number>) {
|
|
|
162
163
|
|
|
163
164
|
The remaining helper names follow the same rule: `getPageList` is the plain non-reactive list request, and `getDelayedPageMetric` is the intentionally slow metric request used for dedupe demonstrations.
|
|
164
165
|
|
|
166
|
+
## Upgrading From 4.4.x
|
|
167
|
+
|
|
168
|
+
- Nuxt `>= 4.5.0` is required.
|
|
169
|
+
- Calls made in `setup` during client-side navigation now go through `useAsyncData`, so `lazy: true` no longer blocks navigation and `server`/`enabled` follow Nuxt's rules. Calls from event handlers, `onMounted`, or watchers still use the compatibility mode.
|
|
170
|
+
- Errors thrown by `useAsyncData` are no longer swallowed and turned into a fallback.
|
|
171
|
+
- Requests are sent with `query` only; `params` is merged into it. Interceptors still see `options.params`, which ofetch mirrors from `query`.
|
|
172
|
+
- Generated keys changed because they now use `hashKey`. Only code that hard-coded a generated key (for example in `useNuxtData`) needs updating.
|
|
173
|
+
- `error` is typed as `NuxtError<unknown> | undefined` by default.
|
|
174
|
+
|
|
165
175
|
## Request Semantics
|
|
166
176
|
|
|
167
177
|
### Key generation and dedupe
|
|
168
178
|
|
|
169
|
-
- Without an explicit `key`, the module hashes `url + method + resolved request options`.
|
|
170
|
-
- Both `params` and `query` participate in the generated key.
|
|
179
|
+
- Without an explicit `key`, the module hashes `url + method + resolved request options` with Nuxt's `hashKey`.
|
|
180
|
+
- Both `params` and `query` participate in the generated key (they are merged into `query` before hashing).
|
|
181
|
+
- `FormData` bodies are hashed by their ordered entries (files as `name:size:lastModified`) and `URLSearchParams` bodies by their entries, so different uploads never share a key.
|
|
171
182
|
- `immutableKey: true` makes the generated key depend only on the URL.
|
|
172
183
|
- If you need exact cache control, provide your own `key`.
|
|
173
184
|
- Same key means shared async-data state.
|
|
@@ -183,13 +194,12 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
183
194
|
### Handler behavior
|
|
184
195
|
|
|
185
196
|
- `handler` receives a merged object built from `params` and `query`.
|
|
186
|
-
-
|
|
187
|
-
-
|
|
188
|
-
- Set `useHandler: false` on a request to bypass preprocessing.
|
|
197
|
+
- The processed output is always sent as `query`. `params` is ofetch's deprecated alias of `query`, so it is only read as input and never forwarded on its own.
|
|
198
|
+
- Set `useHandler: false` on a request to bypass preprocessing; the merged object is still sent as `query`.
|
|
189
199
|
|
|
190
200
|
### Client compatibility mode
|
|
191
201
|
|
|
192
|
-
- Client calls made after mount reuse existing same-key async-data state when available.
|
|
202
|
+
- Client calls made after mount reuse existing same-key async-data state when available, and still get the full `AsyncData` shape (`refresh`, `execute`, and `clear` included).
|
|
193
203
|
- If no Nuxt-managed keyed state exists yet, the module creates and caches a compatibility async-data instance by key.
|
|
194
204
|
- `refresh`, `execute`, `clear`, `watch`, status updates, and cancellation still work in this mode.
|
|
195
205
|
- This mode should not be treated as a full SSR payload cache replacement.
|
|
@@ -200,7 +210,7 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
200
210
|
const ajax = new CustomFetch({
|
|
201
211
|
baseURL: '',
|
|
202
212
|
immutableKey: false,
|
|
203
|
-
showLogs:
|
|
213
|
+
showLogs: import.meta.dev,
|
|
204
214
|
useHandler: true,
|
|
205
215
|
handler: undefined,
|
|
206
216
|
onRequest: undefined,
|
|
@@ -217,11 +227,14 @@ Available methods:
|
|
|
217
227
|
- `ajax.post(url, config?, asyncDataOptions?)`
|
|
218
228
|
- `ajax.request(url, { method, ...config }, asyncDataOptions?)`
|
|
219
229
|
|
|
220
|
-
The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, and `
|
|
230
|
+
The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, `timeout`, and `enabled` options you already know from `useAsyncData`.
|
|
231
|
+
|
|
232
|
+
`showLogs` defaults to `true` in development and prints each client request with `console.info` (real problems such as an unserializable body still use `console.warn`). Set `showLogs: false` to silence it.
|
|
221
233
|
|
|
222
234
|
## Typing Notes
|
|
223
235
|
|
|
224
236
|
- `CustomFetch` mirrors Nuxt async-data generics closely enough for `default`, `pick`, and `transform` to narrow the final `data` type.
|
|
237
|
+
- `error` defaults to `NuxtError<unknown> | undefined`, like `useAsyncData`; the second generic (`NuxtErrorDataT`) types `error.data`.
|
|
225
238
|
- Playground examples and type tests cover explicit generics, default values, and reactive arguments.
|
|
226
239
|
- If you want a custom wrapper with only shared defaults, Nuxt's `createUseFetch` and `createUseAsyncData` remain the simpler choice.
|
|
227
240
|
|
package/dist/module.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { NuxtModule } from 'nuxt/schema';
|
|
2
2
|
|
|
3
3
|
interface ModuleOptions {
|
|
4
4
|
}
|
|
5
|
-
declare const
|
|
5
|
+
declare const nuxtCustomFetch: NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
6
6
|
|
|
7
|
-
export {
|
|
7
|
+
export { nuxtCustomFetch as default };
|
|
8
8
|
export type { ModuleOptions };
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { fileURLToPath } from 'node:url';
|
|
2
2
|
import { defineNuxtModule, createResolver, addImports } from '@nuxt/kit';
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const nuxtCustomFetch = defineNuxtModule({
|
|
5
5
|
meta: {
|
|
6
6
|
name: "nuxt-custom-fetch",
|
|
7
7
|
configKey: "customFetch",
|
|
8
|
-
version: ">=4.
|
|
8
|
+
version: ">=4.5.0"
|
|
9
9
|
},
|
|
10
10
|
defaults: {},
|
|
11
11
|
setup(options, nuxt) {
|
|
@@ -19,4 +19,4 @@ const module$1 = defineNuxtModule({
|
|
|
19
19
|
}
|
|
20
20
|
});
|
|
21
21
|
|
|
22
|
-
export {
|
|
22
|
+
export { nuxtCustomFetch as default };
|
package/dist/runtime/ajax.d.ts
CHANGED
|
@@ -18,11 +18,11 @@ export declare class CustomFetch {
|
|
|
18
18
|
constructor(config: CustomFetchOptions);
|
|
19
19
|
private baseConfig;
|
|
20
20
|
private resolveFetchConfig;
|
|
21
|
-
request<ResT, NuxtErrorDataT =
|
|
22
|
-
request<ResT, NuxtErrorDataT =
|
|
23
|
-
get<ResT, NuxtErrorDataT =
|
|
24
|
-
get<ResT, NuxtErrorDataT =
|
|
25
|
-
post<ResT, NuxtErrorDataT =
|
|
26
|
-
post<ResT, NuxtErrorDataT =
|
|
21
|
+
request<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config: CustomFetchRequestOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
22
|
+
request<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config: CustomFetchRequestOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
23
|
+
get<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
24
|
+
get<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
25
|
+
post<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
26
|
+
post<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(url: NitroFetchRequest, config?: CustomFetchOptions, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): CustomFetchReturnValue<DataT, PickKeys, DefaultT, NuxtErrorDataT>;
|
|
27
27
|
}
|
|
28
28
|
export {};
|
package/dist/runtime/ajax.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { serialize } from "ohash";
|
|
2
|
+
import { hashKey } from "#app";
|
|
2
3
|
import { asyncDataDefaults, granularCachedData, pendingWhenIdle } from "#build/nuxt.config.mjs";
|
|
3
|
-
import { clearNuxtData, computed, createError, getCurrentScope, isRef, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
|
|
4
|
+
import { clearNuxtData, computed, createError, getCurrentInstance, getCurrentScope, isRef, onScopeDispose, reactive, ref, shallowRef, toValue, unref, useAsyncData, useNuxtApp, useRequestFetch, useRuntimeConfig, watch } from "#imports";
|
|
4
5
|
import { generateOptionSegments, Noop, pick, resolveReactiveValue } from "./utils.js";
|
|
5
6
|
const _cachedController = /* @__PURE__ */ new Map();
|
|
6
7
|
const _cachedClientAsyncData = /* @__PURE__ */ new Map();
|
|
7
8
|
const MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES = 50;
|
|
8
|
-
const REPLACE_REG = /[-_]/g;
|
|
9
|
-
const FALLBACK_TO_CLIENT_ASYNC_DATA_RE = /component is already mounted|outside of a plugin|outside of a nuxt instance|requires access to the nuxt instance/i;
|
|
10
9
|
function createAbortController() {
|
|
11
10
|
return typeof AbortController !== "undefined" ? new AbortController() : void 0;
|
|
12
11
|
}
|
|
@@ -34,9 +33,6 @@ function createMergedSignal(signals, timeout) {
|
|
|
34
33
|
}
|
|
35
34
|
return controller.signal;
|
|
36
35
|
}
|
|
37
|
-
function shouldFallbackToClientAsyncData(error) {
|
|
38
|
-
return error instanceof Error && FALLBACK_TO_CLIENT_ASYNC_DATA_RE.test(error.message);
|
|
39
|
-
}
|
|
40
36
|
function pruneClientAsyncDataCache() {
|
|
41
37
|
while (_cachedClientAsyncData.size > MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES) {
|
|
42
38
|
const oldestEntry = _cachedClientAsyncData.entries().next().value;
|
|
@@ -47,6 +43,24 @@ function pruneClientAsyncDataCache() {
|
|
|
47
43
|
asyncData.clear();
|
|
48
44
|
}
|
|
49
45
|
}
|
|
46
|
+
function toClientAsyncDataEntry(key, entry) {
|
|
47
|
+
const execute = async (opts) => {
|
|
48
|
+
await entry.execute(opts);
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
data: entry.data,
|
|
52
|
+
error: entry.error,
|
|
53
|
+
pending: entry.pending,
|
|
54
|
+
status: entry.status,
|
|
55
|
+
execute,
|
|
56
|
+
refresh: execute,
|
|
57
|
+
clear: () => {
|
|
58
|
+
entry._abortController?.abort(new DOMException("AsyncData aborted by user.", "AbortError"));
|
|
59
|
+
entry._abortController = void 0;
|
|
60
|
+
clearNuxtData(key);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
50
64
|
export function __resetCustomFetchCaches() {
|
|
51
65
|
for (const controller of _cachedController.values()) {
|
|
52
66
|
controller.abort();
|
|
@@ -89,18 +103,17 @@ export class CustomFetch {
|
|
|
89
103
|
const query = resolveReactiveValue(toValue(config.query)) || {};
|
|
90
104
|
const params = resolveReactiveValue(toValue(config.params)) || {};
|
|
91
105
|
const baseHandler = handler || this._baseHandler;
|
|
92
|
-
const _name = Object.keys(query).length ? "query" : "params";
|
|
93
106
|
const mergeObj = {
|
|
94
107
|
...params,
|
|
95
108
|
...query
|
|
96
109
|
};
|
|
97
110
|
if (useHandler && baseHandler && typeof baseHandler === "function") {
|
|
98
|
-
return {
|
|
111
|
+
return { query: baseHandler(mergeObj) };
|
|
99
112
|
}
|
|
100
|
-
return {
|
|
113
|
+
return { query: { ...mergeObj } };
|
|
101
114
|
}
|
|
102
115
|
resolveFetchConfig(config, timeout) {
|
|
103
|
-
const { handler: _handler, useHandler: _useHandler, ...rawConfig } = config;
|
|
116
|
+
const { handler: _handler, useHandler: _useHandler, params: _params, ...rawConfig } = config;
|
|
104
117
|
const baseConfig = this.baseConfig(config);
|
|
105
118
|
const baseURL = toValue(rawConfig.baseURL);
|
|
106
119
|
const body = resolveReactiveValue(toValue(rawConfig.body));
|
|
@@ -108,8 +121,7 @@ export class CustomFetch {
|
|
|
108
121
|
const cache = typeof _cache === "boolean" ? void 0 : _cache;
|
|
109
122
|
const headers = resolveReactiveValue(toValue(rawConfig.headers));
|
|
110
123
|
const method = toValue(rawConfig.method);
|
|
111
|
-
const
|
|
112
|
-
const query = resolveReactiveValue(toValue(baseConfig.query ?? rawConfig.query));
|
|
124
|
+
const query = resolveReactiveValue(toValue(baseConfig.query));
|
|
113
125
|
return {
|
|
114
126
|
...rawConfig,
|
|
115
127
|
...baseConfig,
|
|
@@ -118,7 +130,6 @@ export class CustomFetch {
|
|
|
118
130
|
cache,
|
|
119
131
|
headers,
|
|
120
132
|
method,
|
|
121
|
-
params,
|
|
122
133
|
query,
|
|
123
134
|
timeout
|
|
124
135
|
};
|
|
@@ -166,7 +177,6 @@ export class CustomFetch {
|
|
|
166
177
|
headers: initialFetchConfig.headers,
|
|
167
178
|
key: toValue(resolvedConfig.key),
|
|
168
179
|
method: initialFetchConfig.method,
|
|
169
|
-
params: initialFetchConfig.params,
|
|
170
180
|
query: initialFetchConfig.query
|
|
171
181
|
}).filter(([, value]) => value !== void 0));
|
|
172
182
|
let bodyLogs;
|
|
@@ -175,7 +185,7 @@ export class CustomFetch {
|
|
|
175
185
|
} catch (error) {
|
|
176
186
|
console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
|
|
177
187
|
}
|
|
178
|
-
console.
|
|
188
|
+
console.info([
|
|
179
189
|
"\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 [Custom Fetch] \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014",
|
|
180
190
|
`[Request URL]: ${url}`,
|
|
181
191
|
"",
|
|
@@ -230,8 +240,8 @@ export class CustomFetch {
|
|
|
230
240
|
method: initialFetchConfig.method ?? resolvedConfig.method
|
|
231
241
|
}));
|
|
232
242
|
}
|
|
233
|
-
const
|
|
234
|
-
const key = computed(() => toValue(resolvedConfig.key) ||
|
|
243
|
+
const defaultKey = hashKey(hashValue).slice(0, 10);
|
|
244
|
+
const key = computed(() => toValue(resolvedConfig.key) || defaultKey);
|
|
235
245
|
const executeRequest = (executeOptions = {}) => {
|
|
236
246
|
const timeout = executeOptions.timeout ?? options.timeout;
|
|
237
247
|
const signal = createMergedSignal([executeOptions.signal], timeout);
|
|
@@ -282,8 +292,9 @@ export class CustomFetch {
|
|
|
282
292
|
let keyChanging = false;
|
|
283
293
|
let stopKeyWatch;
|
|
284
294
|
let stopOptionWatch;
|
|
295
|
+
let stopEnabledWatch;
|
|
285
296
|
let stopRefreshHook;
|
|
286
|
-
const initialStatus = options.immediate === false ? "idle" : "pending";
|
|
297
|
+
const initialStatus = options.immediate === false || toValue(options.enabled) === false ? "idle" : "pending";
|
|
287
298
|
const statusRef = _ref(initialStatus);
|
|
288
299
|
const pendingRef = usePendingRef ? _ref(initialStatus === "pending") : computed(() => statusRef.value === "pending");
|
|
289
300
|
const setPending = (value) => {
|
|
@@ -296,6 +307,8 @@ export class CustomFetch {
|
|
|
296
307
|
stopKeyWatch = void 0;
|
|
297
308
|
stopOptionWatch?.();
|
|
298
309
|
stopOptionWatch = void 0;
|
|
310
|
+
stopEnabledWatch?.();
|
|
311
|
+
stopEnabledWatch = void 0;
|
|
299
312
|
stopRefreshHook?.();
|
|
300
313
|
stopRefreshHook = void 0;
|
|
301
314
|
};
|
|
@@ -342,6 +355,9 @@ export class CustomFetch {
|
|
|
342
355
|
return;
|
|
343
356
|
}
|
|
344
357
|
}
|
|
358
|
+
if (toValue(options.enabled) === false) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
345
361
|
const currentRequestId = ++requestId;
|
|
346
362
|
const controller = createAbortController();
|
|
347
363
|
activeController = controller;
|
|
@@ -396,6 +412,20 @@ export class CustomFetch {
|
|
|
396
412
|
await activeRequest;
|
|
397
413
|
}
|
|
398
414
|
};
|
|
415
|
+
const cancelActiveRequest = (reason) => {
|
|
416
|
+
if (!activeRequest) {
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
requestId++;
|
|
420
|
+
activeController?.abort(new DOMException(reason, "AbortError"));
|
|
421
|
+
activeRequest = void 0;
|
|
422
|
+
activeController = void 0;
|
|
423
|
+
_cachedController.delete(key.value);
|
|
424
|
+
if (asyncData.status.value === "pending") {
|
|
425
|
+
asyncData.status.value = "idle";
|
|
426
|
+
}
|
|
427
|
+
setPending(false);
|
|
428
|
+
};
|
|
399
429
|
_cachedClientAsyncData.set(key.value, asyncData);
|
|
400
430
|
stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
|
|
401
431
|
if (!keys || keys.includes(key.value)) {
|
|
@@ -436,11 +466,21 @@ export class CustomFetch {
|
|
|
436
466
|
await asyncData.refresh({ cause: "watch" });
|
|
437
467
|
}, { flush: "post" });
|
|
438
468
|
}
|
|
469
|
+
if (isRef(options.enabled) || typeof options.enabled === "function") {
|
|
470
|
+
stopEnabledWatch = watch(() => toValue(options.enabled), (isEnabled) => {
|
|
471
|
+
if (!isEnabled) {
|
|
472
|
+
cancelActiveRequest("AsyncData request cancelled by `enabled: false`");
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
439
476
|
if (!hasScope) {
|
|
440
477
|
pruneClientAsyncDataCache();
|
|
441
478
|
}
|
|
442
479
|
if (hasScope) {
|
|
443
|
-
onScopeDispose(
|
|
480
|
+
onScopeDispose(() => {
|
|
481
|
+
stopWatchers();
|
|
482
|
+
cancelActiveRequest("AsyncData request cancelled by unmount");
|
|
483
|
+
});
|
|
444
484
|
}
|
|
445
485
|
if (options.immediate === false) {
|
|
446
486
|
return Promise.resolve(asyncData);
|
|
@@ -449,36 +489,21 @@ export class CustomFetch {
|
|
|
449
489
|
};
|
|
450
490
|
const sharedAsyncData = nuxtApp._asyncData?.[key.value];
|
|
451
491
|
const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
dedupe: options.dedupe
|
|
457
|
-
});
|
|
458
|
-
return sharedAsyncData;
|
|
459
|
-
}
|
|
460
|
-
if (cachedClientAsyncData) {
|
|
492
|
+
const instance = getCurrentInstance();
|
|
493
|
+
if (import.meta.client && !nuxtApp.isHydrating && !nuxtApp._processingMiddleware && (!instance || instance.isMounted)) {
|
|
494
|
+
const reusableAsyncData = sharedAsyncData?._deps && typeof sharedAsyncData.execute === "function" ? toClientAsyncDataEntry(key.value, sharedAsyncData) : cachedClientAsyncData;
|
|
495
|
+
if (reusableAsyncData) {
|
|
461
496
|
if (options.immediate === false) {
|
|
462
|
-
return Promise.resolve(
|
|
497
|
+
return Promise.resolve(reusableAsyncData);
|
|
463
498
|
}
|
|
464
|
-
return
|
|
499
|
+
return reusableAsyncData.execute({
|
|
465
500
|
cause: "initial",
|
|
466
501
|
dedupe: options.dedupe
|
|
467
|
-
}).then(() =>
|
|
468
|
-
}
|
|
469
|
-
return createClientAsyncDataFallback();
|
|
470
|
-
}
|
|
471
|
-
try {
|
|
472
|
-
return useAsyncData(key, _handler, options);
|
|
473
|
-
} catch (error) {
|
|
474
|
-
if (!import.meta.client || !shouldFallbackToClientAsyncData(error)) {
|
|
475
|
-
throw error;
|
|
476
|
-
}
|
|
477
|
-
if (import.meta.dev) {
|
|
478
|
-
console.warn("[Custom Fetch] Falling back to client compatibility mode outside setup-compatible async data context.");
|
|
502
|
+
}).then(() => reusableAsyncData);
|
|
479
503
|
}
|
|
480
504
|
return createClientAsyncDataFallback();
|
|
481
505
|
}
|
|
506
|
+
return useAsyncData(key, _handler, options);
|
|
482
507
|
}
|
|
483
508
|
get(url, config = {}, options) {
|
|
484
509
|
return this.request(url, {
|
package/dist/runtime/type.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { MaybeRefOrGetter } from '#imports';
|
|
2
1
|
import type { FetchOptions } from 'ofetch';
|
|
2
|
+
import type { MaybeRefOrGetter } from '#imports';
|
|
3
3
|
export type { FetchContext, FetchResponse } from 'ofetch';
|
|
4
4
|
type NativeFetchValue = ArrayBuffer | Blob | Date | File | FormData | Headers | Request | URLSearchParams;
|
|
5
5
|
export type MaybeRefDeep<T> = T extends (...args: any[]) => any ? T : T extends NativeFetchValue ? MaybeRefOrGetter<T> : T extends Array<infer U> ? MaybeRefOrGetter<Array<MaybeRefDeep<U>>> : T extends ReadonlyArray<infer U> ? MaybeRefOrGetter<ReadonlyArray<MaybeRefDeep<U>>> : T extends object ? MaybeRefOrGetter<{
|
package/dist/runtime/utils.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { toValue } from "#imports";
|
|
2
1
|
import { isPlainObject } from "@vue/shared";
|
|
3
|
-
import {
|
|
2
|
+
import { hashKey } from "#app";
|
|
3
|
+
import { toValue } from "#imports";
|
|
4
4
|
export function Noop() {
|
|
5
5
|
}
|
|
6
6
|
function getGlobalConstructor(name) {
|
|
@@ -69,21 +69,23 @@ export function generateOptionSegments(opts) {
|
|
|
69
69
|
if (opts.body !== void 0) {
|
|
70
70
|
const value = resolveReactiveValue(toValue(opts.body));
|
|
71
71
|
if (!value) {
|
|
72
|
-
segments.push(
|
|
72
|
+
segments.push(hashKey(value));
|
|
73
73
|
} else if (value instanceof ArrayBuffer) {
|
|
74
|
-
segments.push(
|
|
74
|
+
segments.push(hashKey(Object.fromEntries(Array.from(new Uint8Array(value).entries(), ([key, item]) => [key, item.toString()]))));
|
|
75
75
|
} else if (isFormDataValue(value)) {
|
|
76
|
-
const
|
|
76
|
+
const entries = [];
|
|
77
77
|
for (const entry of value.entries()) {
|
|
78
78
|
const [key, val] = entry;
|
|
79
|
-
|
|
79
|
+
entries.push([key, isFileValue(val) ? `${val.name}:${val.size}:${val.lastModified}` : val]);
|
|
80
80
|
}
|
|
81
|
-
segments.push(
|
|
81
|
+
segments.push(hashKey(entries));
|
|
82
|
+
} else if (isURLSearchParamsValue(value)) {
|
|
83
|
+
segments.push(hashKey(Array.from(value.entries())));
|
|
82
84
|
} else if (isPlainObject(value)) {
|
|
83
|
-
segments.push(
|
|
85
|
+
segments.push(hashKey(resolveReactiveValue(value)));
|
|
84
86
|
} else {
|
|
85
87
|
try {
|
|
86
|
-
segments.push(
|
|
88
|
+
segments.push(hashKey(value));
|
|
87
89
|
} catch {
|
|
88
90
|
console.warn("[Custom Fetch] Failed to hash body", value);
|
|
89
91
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-custom-fetch",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.5.0",
|
|
5
5
|
"packageManager": "pnpm@11.7.0",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"test:types": "tsc -p tsconfig.json --noEmit",
|
|
33
33
|
"prepare": "husky",
|
|
34
34
|
"commit": "git-cz",
|
|
35
|
-
"
|
|
35
|
+
"release:alpha": "changelogen --release --prerelease && pnpm prepack && npm publish --tag alpha && git push --follow-tags",
|
|
36
36
|
"release": "changelogen --release && pnpm prepack && npm publish && git push --follow-tags"
|
|
37
37
|
},
|
|
38
38
|
"config": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
|
-
"nuxt": ">=4.
|
|
44
|
+
"nuxt": ">=4.5.0",
|
|
45
45
|
"vue": "^3.5.30"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
@@ -52,9 +52,9 @@
|
|
|
52
52
|
"@antfu/eslint-config": "^9.0.0",
|
|
53
53
|
"@commitlint/cli": "^21.0.2",
|
|
54
54
|
"@commitlint/config-conventional": "^21.0.2",
|
|
55
|
-
"@nuxt/kit": "4.
|
|
55
|
+
"@nuxt/kit": "4.5.2",
|
|
56
56
|
"@nuxt/module-builder": "^1.0.2",
|
|
57
|
-
"@nuxt/schema": "4.
|
|
57
|
+
"@nuxt/schema": "4.5.2",
|
|
58
58
|
"@types/node": "^25.5.0",
|
|
59
59
|
"@vitest/coverage-v8": "^4.1.9",
|
|
60
60
|
"changelogen": "^0.6.2",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"husky": "^9.1.7",
|
|
65
65
|
"nano-staged": "^1.0.2",
|
|
66
66
|
"nitropack": "^2.13.1",
|
|
67
|
-
"nuxt": "4.
|
|
67
|
+
"nuxt": "4.5.2",
|
|
68
68
|
"typescript": "6.0.3",
|
|
69
69
|
"vitest": "^4.1.9",
|
|
70
70
|
"vue": "^3.5.30"
|