nuxt-custom-fetch 4.4.8 → 4.6.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 +34 -15
- package/dist/module.d.mts +3 -3
- package/dist/module.json +5 -2
- package/dist/module.mjs +5 -3
- package/dist/runtime/ajax.d.ts +6 -6
- package/dist/runtime/ajax.js +97 -47
- package/dist/runtime/type.d.ts +1 -1
- package/dist/runtime/utils.js +11 -9
- package/package.json +26 -29
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,9 +14,11 @@ Use `CustomFetch` when you specifically need an extra request layer on top of th
|
|
|
14
14
|
|
|
15
15
|
## Compatibility
|
|
16
16
|
|
|
17
|
-
- `v4`: Nuxt
|
|
17
|
+
- `v4`: Nuxt `^4.5.0` (Nuxt 4 only)
|
|
18
18
|
- `v2`: Nuxt `3.0.0` to `3.16.x`
|
|
19
19
|
|
|
20
|
+
The development playground targets Nuxt `4.6.2` and Vue `3.5.44`. Nuxt `4.6.2` requires Node.js `^22.22.3 || ^24.15.0 || >=26.0.0`. Nuxt 5 is still in development and is not included in this module's compatibility range.
|
|
21
|
+
|
|
20
22
|
## Current Maintenance Summary
|
|
21
23
|
|
|
22
24
|
The current implementation is maintained around these guarantees:
|
|
@@ -24,9 +26,11 @@ The current implementation is maintained around these guarantees:
|
|
|
24
26
|
- runtime behavior is aligned with Nuxt 4 async-data semantics where possible
|
|
25
27
|
- public method generics follow Nuxt `AsyncData` typing more closely
|
|
26
28
|
- 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
|
|
29
|
+
- 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
30
|
- same-key client compatibility requests share one async-data bucket, so `dedupe: 'cancel'` can abort the previous pending request
|
|
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`
|
|
31
|
+
- 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` unless `serialize: false` is set
|
|
32
|
+
- 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
|
|
33
|
+
- on Nuxt 4.6, the client compatibility path also honors async-data `middleware` (first entry outermost, before `transform`/`pick`) and `serialize: false`, including cached results
|
|
30
34
|
- 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
35
|
- Vitest runtime tests and TypeScript type tests cover the wrapper behavior
|
|
32
36
|
|
|
@@ -40,7 +44,7 @@ The current implementation is maintained around these guarantees:
|
|
|
40
44
|
- param or query preprocessing through `handler`
|
|
41
45
|
- one request API that still works after mount on the client
|
|
42
46
|
|
|
43
|
-
If all you need is a typed composable with shared defaults, prefer Nuxt's official factories:
|
|
47
|
+
If all you need is a typed composable with shared defaults, prefer Nuxt's official factories. Nuxt 4.6 also adds `defineUseFetchAddon` and `defineUseAsyncDataAddon` for reusable options, middleware, and return-value extensions:
|
|
44
48
|
|
|
45
49
|
```ts
|
|
46
50
|
export const useAPI = createUseFetch({
|
|
@@ -55,11 +59,11 @@ export const useCachedData = createUseAsyncData({
|
|
|
55
59
|
|
|
56
60
|
## How It Works
|
|
57
61
|
|
|
58
|
-
- In `setup
|
|
59
|
-
- After
|
|
62
|
+
- 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.
|
|
63
|
+
- 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
64
|
- The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
|
|
61
65
|
- The compatibility mode is not a full SSR payload or cache replacement.
|
|
62
|
-
- Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules.
|
|
66
|
+
- Calls that intentionally share the same `key` should keep `handler`, `deep`, `transform`, `pick`, `getCachedData`, and `default` consistent, matching Nuxt's keyed async-data rules. On Nuxt 4.6, keep `middleware` and `serialize` consistent too.
|
|
63
67
|
|
|
64
68
|
## Installation
|
|
65
69
|
|
|
@@ -162,12 +166,22 @@ export function getReactivePageList (page: Ref<number>) {
|
|
|
162
166
|
|
|
163
167
|
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
168
|
|
|
169
|
+
## Upgrading From 4.4.x
|
|
170
|
+
|
|
171
|
+
- Nuxt `^4.5.0` is required.
|
|
172
|
+
- 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.
|
|
173
|
+
- Errors thrown by `useAsyncData` are no longer swallowed and turned into a fallback.
|
|
174
|
+
- Requests are sent with `query` only; `params` is merged into it. Interceptors still see `options.params`, which ofetch mirrors from `query`.
|
|
175
|
+
- Generated keys changed because they now use `hashKey`. Only code that hard-coded a generated key (for example in `useNuxtData`) needs updating.
|
|
176
|
+
- `error` is typed as `NuxtError<unknown> | undefined` by default.
|
|
177
|
+
|
|
165
178
|
## Request Semantics
|
|
166
179
|
|
|
167
180
|
### Key generation and dedupe
|
|
168
181
|
|
|
169
|
-
- Without an explicit `key`, the module hashes `url + method + resolved request options`.
|
|
170
|
-
- Both `params` and `query` participate in the generated key.
|
|
182
|
+
- Without an explicit `key`, the module hashes `url + method + resolved request options` with Nuxt's `hashKey`.
|
|
183
|
+
- Both `params` and `query` participate in the generated key (they are merged into `query` before hashing).
|
|
184
|
+
- `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
185
|
- `immutableKey: true` makes the generated key depend only on the URL.
|
|
172
186
|
- If you need exact cache control, provide your own `key`.
|
|
173
187
|
- Same key means shared async-data state.
|
|
@@ -183,13 +197,12 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
183
197
|
### Handler behavior
|
|
184
198
|
|
|
185
199
|
- `handler` receives a merged object built from `params` and `query`.
|
|
186
|
-
-
|
|
187
|
-
-
|
|
188
|
-
- Set `useHandler: false` on a request to bypass preprocessing.
|
|
200
|
+
- 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.
|
|
201
|
+
- Set `useHandler: false` on a request to bypass preprocessing; the merged object is still sent as `query`.
|
|
189
202
|
|
|
190
203
|
### Client compatibility mode
|
|
191
204
|
|
|
192
|
-
- Client calls made after mount reuse existing same-key async-data state when available.
|
|
205
|
+
- 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
206
|
- If no Nuxt-managed keyed state exists yet, the module creates and caches a compatibility async-data instance by key.
|
|
194
207
|
- `refresh`, `execute`, `clear`, `watch`, status updates, and cancellation still work in this mode.
|
|
195
208
|
- This mode should not be treated as a full SSR payload cache replacement.
|
|
@@ -200,7 +213,7 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
200
213
|
const ajax = new CustomFetch({
|
|
201
214
|
baseURL: '',
|
|
202
215
|
immutableKey: false,
|
|
203
|
-
showLogs:
|
|
216
|
+
showLogs: import.meta.dev,
|
|
204
217
|
useHandler: true,
|
|
205
218
|
handler: undefined,
|
|
206
219
|
onRequest: undefined,
|
|
@@ -217,11 +230,14 @@ Available methods:
|
|
|
217
230
|
- `ajax.post(url, config?, asyncDataOptions?)`
|
|
218
231
|
- `ajax.request(url, { method, ...config }, asyncDataOptions?)`
|
|
219
232
|
|
|
220
|
-
The return value follows Nuxt's `AsyncData<...>` shape and can use the same `default`, `pick`, `transform`, `watch`, `dedupe`, and `
|
|
233
|
+
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`. Nuxt 4.6 additionally provides `serialize` and `middleware`.
|
|
234
|
+
|
|
235
|
+
`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
236
|
|
|
222
237
|
## Typing Notes
|
|
223
238
|
|
|
224
239
|
- `CustomFetch` mirrors Nuxt async-data generics closely enough for `default`, `pick`, and `transform` to narrow the final `data` type.
|
|
240
|
+
- `error` defaults to `NuxtError<unknown> | undefined`, like `useAsyncData`; the second generic (`NuxtErrorDataT`) types `error.data`.
|
|
225
241
|
- Playground examples and type tests cover explicit generics, default values, and reactive arguments.
|
|
226
242
|
- If you want a custom wrapper with only shared defaults, Nuxt's `createUseFetch` and `createUseAsyncData` remain the simpler choice.
|
|
227
243
|
|
|
@@ -243,6 +259,9 @@ The return value follows Nuxt's `AsyncData<...>` shape and can use the same `def
|
|
|
243
259
|
|
|
244
260
|
## References
|
|
245
261
|
|
|
262
|
+
- https://github.com/nuxt/nuxt/releases/tag/v4.6.0
|
|
263
|
+
- https://github.com/nuxt/nuxt/releases/tag/v4.6.2
|
|
264
|
+
- https://nuxt.com/docs/4.x/api/utils/define-use-fetch-addon
|
|
246
265
|
- https://nuxt.com/docs/4.x/api/composables/create-use-async-data
|
|
247
266
|
- https://nuxt.com/docs/4.x/api/composables/create-use-fetch
|
|
248
267
|
- https://nuxt.com/docs/4.x/api/composables/use-async-data
|
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
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-custom-fetch",
|
|
3
3
|
"configKey": "customFetch",
|
|
4
|
-
"
|
|
4
|
+
"compatibility": {
|
|
5
|
+
"nuxt": "^4.5.0"
|
|
6
|
+
},
|
|
7
|
+
"version": "4.6.0",
|
|
5
8
|
"builder": {
|
|
6
|
-
"@nuxt/module-builder": "1.0.
|
|
9
|
+
"@nuxt/module-builder": "1.0.3",
|
|
7
10
|
"unbuild": "unknown"
|
|
8
11
|
}
|
|
9
12
|
}
|
package/dist/module.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
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
|
-
|
|
8
|
+
compatibility: {
|
|
9
|
+
nuxt: "^4.5.0"
|
|
10
|
+
}
|
|
9
11
|
},
|
|
10
12
|
defaults: {},
|
|
11
13
|
setup(options, nuxt) {
|
|
@@ -19,4 +21,4 @@ const module$1 = defineNuxtModule({
|
|
|
19
21
|
}
|
|
20
22
|
});
|
|
21
23
|
|
|
22
|
-
export {
|
|
24
|
+
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);
|
|
@@ -249,6 +259,7 @@ export class CustomFetch {
|
|
|
249
259
|
};
|
|
250
260
|
const nuxtApp = useNuxtApp();
|
|
251
261
|
const createClientAsyncDataFallback = () => {
|
|
262
|
+
const fallbackOptions = options;
|
|
252
263
|
const _ref = options.deep ? ref : shallowRef;
|
|
253
264
|
const usePendingRef = pendingWhenIdle;
|
|
254
265
|
const getDefaultValue = () => {
|
|
@@ -270,7 +281,7 @@ export class CustomFetch {
|
|
|
270
281
|
return void 0;
|
|
271
282
|
};
|
|
272
283
|
const writePayloadData = (value) => {
|
|
273
|
-
if (nuxtApp.payload?.data) {
|
|
284
|
+
if (fallbackOptions.serialize !== false && nuxtApp.payload?.data) {
|
|
274
285
|
nuxtApp.payload.data[key.value] = value;
|
|
275
286
|
}
|
|
276
287
|
};
|
|
@@ -282,8 +293,9 @@ export class CustomFetch {
|
|
|
282
293
|
let keyChanging = false;
|
|
283
294
|
let stopKeyWatch;
|
|
284
295
|
let stopOptionWatch;
|
|
296
|
+
let stopEnabledWatch;
|
|
285
297
|
let stopRefreshHook;
|
|
286
|
-
const initialStatus = options.immediate === false ? "idle" : "pending";
|
|
298
|
+
const initialStatus = options.immediate === false || toValue(options.enabled) === false ? "idle" : "pending";
|
|
287
299
|
const statusRef = _ref(initialStatus);
|
|
288
300
|
const pendingRef = usePendingRef ? _ref(initialStatus === "pending") : computed(() => statusRef.value === "pending");
|
|
289
301
|
const setPending = (value) => {
|
|
@@ -296,6 +308,8 @@ export class CustomFetch {
|
|
|
296
308
|
stopKeyWatch = void 0;
|
|
297
309
|
stopOptionWatch?.();
|
|
298
310
|
stopOptionWatch = void 0;
|
|
311
|
+
stopEnabledWatch?.();
|
|
312
|
+
stopEnabledWatch = void 0;
|
|
299
313
|
stopRefreshHook?.();
|
|
300
314
|
stopRefreshHook = void 0;
|
|
301
315
|
};
|
|
@@ -342,6 +356,9 @@ export class CustomFetch {
|
|
|
342
356
|
return;
|
|
343
357
|
}
|
|
344
358
|
}
|
|
359
|
+
if (toValue(options.enabled) === false) {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
345
362
|
const currentRequestId = ++requestId;
|
|
346
363
|
const controller = createAbortController();
|
|
347
364
|
activeController = controller;
|
|
@@ -352,10 +369,33 @@ export class CustomFetch {
|
|
|
352
369
|
setPending(true);
|
|
353
370
|
asyncData.status.value = "pending";
|
|
354
371
|
asyncData.error.value = asyncDataDefaults.errorValue;
|
|
355
|
-
|
|
372
|
+
const signal = createMergedSignal([controller?.signal], executeOptions?.timeout ?? options.timeout);
|
|
373
|
+
let run = () => executeRequest({
|
|
356
374
|
...executeOptions,
|
|
357
|
-
signal
|
|
358
|
-
})
|
|
375
|
+
signal
|
|
376
|
+
});
|
|
377
|
+
for (let i = (fallbackOptions.middleware?.length ?? 0) - 1; i >= 0; i--) {
|
|
378
|
+
const middleware = fallbackOptions.middleware[i];
|
|
379
|
+
const next = run;
|
|
380
|
+
run = () => Promise.resolve(middleware(next, { signal }));
|
|
381
|
+
}
|
|
382
|
+
let request;
|
|
383
|
+
let removeAbortListener;
|
|
384
|
+
try {
|
|
385
|
+
request = fallbackOptions.middleware?.length ? new Promise((resolve, reject) => {
|
|
386
|
+
const onAbort = () => reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
387
|
+
if (signal?.aborted) {
|
|
388
|
+
onAbort();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
392
|
+
removeAbortListener = () => signal?.removeEventListener("abort", onAbort);
|
|
393
|
+
Promise.resolve(run()).then(resolve, reject);
|
|
394
|
+
}) : run();
|
|
395
|
+
} catch (error) {
|
|
396
|
+
request = Promise.reject(error);
|
|
397
|
+
}
|
|
398
|
+
activeRequest = request.then(async (result) => {
|
|
359
399
|
if (currentRequestId !== requestId) {
|
|
360
400
|
return;
|
|
361
401
|
}
|
|
@@ -382,6 +422,7 @@ export class CustomFetch {
|
|
|
382
422
|
asyncData.data.value = getDefaultValue();
|
|
383
423
|
asyncData.status.value = "error";
|
|
384
424
|
}).finally(() => {
|
|
425
|
+
removeAbortListener?.();
|
|
385
426
|
if (currentRequestId !== requestId) {
|
|
386
427
|
return;
|
|
387
428
|
}
|
|
@@ -396,6 +437,20 @@ export class CustomFetch {
|
|
|
396
437
|
await activeRequest;
|
|
397
438
|
}
|
|
398
439
|
};
|
|
440
|
+
const cancelActiveRequest = (reason) => {
|
|
441
|
+
if (!activeRequest) {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
requestId++;
|
|
445
|
+
activeController?.abort(new DOMException(reason, "AbortError"));
|
|
446
|
+
activeRequest = void 0;
|
|
447
|
+
activeController = void 0;
|
|
448
|
+
_cachedController.delete(key.value);
|
|
449
|
+
if (asyncData.status.value === "pending") {
|
|
450
|
+
asyncData.status.value = "idle";
|
|
451
|
+
}
|
|
452
|
+
setPending(false);
|
|
453
|
+
};
|
|
399
454
|
_cachedClientAsyncData.set(key.value, asyncData);
|
|
400
455
|
stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
|
|
401
456
|
if (!keys || keys.includes(key.value)) {
|
|
@@ -436,11 +491,21 @@ export class CustomFetch {
|
|
|
436
491
|
await asyncData.refresh({ cause: "watch" });
|
|
437
492
|
}, { flush: "post" });
|
|
438
493
|
}
|
|
494
|
+
if (isRef(options.enabled) || typeof options.enabled === "function") {
|
|
495
|
+
stopEnabledWatch = watch(() => toValue(options.enabled), (isEnabled) => {
|
|
496
|
+
if (!isEnabled) {
|
|
497
|
+
cancelActiveRequest("AsyncData request cancelled by `enabled: false`");
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
}
|
|
439
501
|
if (!hasScope) {
|
|
440
502
|
pruneClientAsyncDataCache();
|
|
441
503
|
}
|
|
442
504
|
if (hasScope) {
|
|
443
|
-
onScopeDispose(
|
|
505
|
+
onScopeDispose(() => {
|
|
506
|
+
stopWatchers();
|
|
507
|
+
cancelActiveRequest("AsyncData request cancelled by unmount");
|
|
508
|
+
});
|
|
444
509
|
}
|
|
445
510
|
if (options.immediate === false) {
|
|
446
511
|
return Promise.resolve(asyncData);
|
|
@@ -449,36 +514,21 @@ export class CustomFetch {
|
|
|
449
514
|
};
|
|
450
515
|
const sharedAsyncData = nuxtApp._asyncData?.[key.value];
|
|
451
516
|
const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
dedupe: options.dedupe
|
|
457
|
-
});
|
|
458
|
-
return sharedAsyncData;
|
|
459
|
-
}
|
|
460
|
-
if (cachedClientAsyncData) {
|
|
517
|
+
const instance = getCurrentInstance();
|
|
518
|
+
if (import.meta.client && !nuxtApp.isHydrating && !nuxtApp._processingMiddleware && (!instance || instance.isMounted)) {
|
|
519
|
+
const reusableAsyncData = sharedAsyncData?._deps && typeof sharedAsyncData.execute === "function" ? toClientAsyncDataEntry(key.value, sharedAsyncData) : cachedClientAsyncData;
|
|
520
|
+
if (reusableAsyncData) {
|
|
461
521
|
if (options.immediate === false) {
|
|
462
|
-
return Promise.resolve(
|
|
522
|
+
return Promise.resolve(reusableAsyncData);
|
|
463
523
|
}
|
|
464
|
-
return
|
|
524
|
+
return reusableAsyncData.execute({
|
|
465
525
|
cause: "initial",
|
|
466
526
|
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.");
|
|
527
|
+
}).then(() => reusableAsyncData);
|
|
479
528
|
}
|
|
480
529
|
return createClientAsyncDataFallback();
|
|
481
530
|
}
|
|
531
|
+
return useAsyncData(key, _handler, options);
|
|
482
532
|
}
|
|
483
533
|
get(url, config = {}, options) {
|
|
484
534
|
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,8 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-custom-fetch",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "4.
|
|
5
|
-
"packageManager": "pnpm@11.7.0",
|
|
4
|
+
"version": "4.6.0",
|
|
6
5
|
"license": "MIT",
|
|
7
6
|
"repository": {
|
|
8
7
|
"type": "git",
|
|
@@ -18,43 +17,26 @@
|
|
|
18
17
|
"files": [
|
|
19
18
|
"dist"
|
|
20
19
|
],
|
|
21
|
-
"scripts": {
|
|
22
|
-
"prepack": "nuxt-module-build build",
|
|
23
|
-
"dev": "nuxi dev playground",
|
|
24
|
-
"dev:build": "nuxi build playground",
|
|
25
|
-
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
|
|
26
|
-
"echo:husky": "echo 'npx nano-staged' > .husky/pre-commit && echo 'npx --no-install commitlint --edit \"$1\"' > .husky/commit-msg",
|
|
27
|
-
"lint": "eslint .",
|
|
28
|
-
"lint:fix": "eslint . --fix",
|
|
29
|
-
"test": "vitest run",
|
|
30
|
-
"test:watch": "vitest",
|
|
31
|
-
"test:coverage": "vitest run --coverage",
|
|
32
|
-
"test:types": "tsc -p tsconfig.json --noEmit",
|
|
33
|
-
"prepare": "husky",
|
|
34
|
-
"commit": "git-cz",
|
|
35
|
-
"prerelease": "changelogen --prerelease && pnpm prepack && npm publish --tag alpha",
|
|
36
|
-
"release": "changelogen --release && pnpm prepack && npm publish && git push --follow-tags"
|
|
37
|
-
},
|
|
38
20
|
"config": {
|
|
39
21
|
"commitizen": {
|
|
40
22
|
"path": "node_modules/cz-git"
|
|
41
23
|
}
|
|
42
24
|
},
|
|
43
25
|
"peerDependencies": {
|
|
44
|
-
"nuxt": "
|
|
26
|
+
"nuxt": "^4.5.0",
|
|
45
27
|
"vue": "^3.5.30"
|
|
46
28
|
},
|
|
47
29
|
"dependencies": {
|
|
48
|
-
"@vue/shared": "^3.5.
|
|
49
|
-
"ohash": "^2.0.
|
|
30
|
+
"@vue/shared": "^3.5.44",
|
|
31
|
+
"ohash": "^2.0.12"
|
|
50
32
|
},
|
|
51
33
|
"devDependencies": {
|
|
52
34
|
"@antfu/eslint-config": "^9.0.0",
|
|
53
35
|
"@commitlint/cli": "^21.0.2",
|
|
54
36
|
"@commitlint/config-conventional": "^21.0.2",
|
|
55
|
-
"@nuxt/kit": "4.
|
|
56
|
-
"@nuxt/module-builder": "^1.0.
|
|
57
|
-
"@nuxt/schema": "4.
|
|
37
|
+
"@nuxt/kit": "4.6.2",
|
|
38
|
+
"@nuxt/module-builder": "^1.0.3",
|
|
39
|
+
"@nuxt/schema": "4.6.2",
|
|
58
40
|
"@types/node": "^25.5.0",
|
|
59
41
|
"@vitest/coverage-v8": "^4.1.9",
|
|
60
42
|
"changelogen": "^0.6.2",
|
|
@@ -63,11 +45,11 @@
|
|
|
63
45
|
"eslint": "^10.0.3",
|
|
64
46
|
"husky": "^9.1.7",
|
|
65
47
|
"nano-staged": "^1.0.2",
|
|
66
|
-
"nitropack": "^2.13.
|
|
67
|
-
"nuxt": "4.
|
|
48
|
+
"nitropack": "^2.13.5",
|
|
49
|
+
"nuxt": "4.6.2",
|
|
68
50
|
"typescript": "6.0.3",
|
|
69
51
|
"vitest": "^4.1.9",
|
|
70
|
-
"vue": "^3.5.
|
|
52
|
+
"vue": "^3.5.44"
|
|
71
53
|
},
|
|
72
54
|
"husky": {
|
|
73
55
|
"hooks": {
|
|
@@ -76,5 +58,20 @@
|
|
|
76
58
|
},
|
|
77
59
|
"nano-staged": {
|
|
78
60
|
"*": "eslint --fix"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"dev": "nuxi dev playground",
|
|
64
|
+
"dev:build": "nuxi build playground",
|
|
65
|
+
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
|
|
66
|
+
"echo:husky": "echo 'npx nano-staged' > .husky/pre-commit && echo 'npx --no-install commitlint --edit \"$1\"' > .husky/commit-msg",
|
|
67
|
+
"lint": "eslint .",
|
|
68
|
+
"lint:fix": "eslint . --fix",
|
|
69
|
+
"test": "vitest run",
|
|
70
|
+
"test:watch": "vitest",
|
|
71
|
+
"test:coverage": "vitest run --coverage",
|
|
72
|
+
"test:types": "tsc -p tsconfig.json --noEmit",
|
|
73
|
+
"commit": "git-cz",
|
|
74
|
+
"release:alpha": "changelogen --release --prerelease && pnpm prepack && npm publish --tag alpha && git push --follow-tags",
|
|
75
|
+
"release": "changelogen --release && pnpm prepack && npm publish && git push --follow-tags"
|
|
79
76
|
}
|
|
80
|
-
}
|
|
77
|
+
}
|