nuxt-custom-fetch 4.4.0 → 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 +28 -13
- 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 +7 -7
- package/dist/runtime/ajax.js +176 -68
- package/dist/runtime/type.d.ts +1 -1
- package/dist/runtime/utils.js +11 -9
- package/package.json +21 -17
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,8 +24,11 @@ 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
|
+
- 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
|
|
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
|
|
29
32
|
- Vitest runtime tests and TypeScript type tests cover the wrapper behavior
|
|
30
33
|
|
|
31
34
|
## When To Use This Module
|
|
@@ -53,8 +56,8 @@ export const useCachedData = createUseAsyncData({
|
|
|
53
56
|
|
|
54
57
|
## How It Works
|
|
55
58
|
|
|
56
|
-
- In `setup
|
|
57
|
-
- 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".
|
|
58
61
|
- The compatibility mode still exposes `data`, `error`, `status`, `pending`, `refresh`, `execute`, and `clear`.
|
|
59
62
|
- The compatibility mode is not a full SSR payload or cache replacement.
|
|
60
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.
|
|
@@ -103,8 +106,8 @@ Always `await` `ajax.get`, `ajax.post`, and `ajax.request` in setup-compatible c
|
|
|
103
106
|
## Reactive Example
|
|
104
107
|
|
|
105
108
|
```ts
|
|
106
|
-
import { CustomFetch } from '#imports'
|
|
107
109
|
import { computed, ref } from 'vue'
|
|
110
|
+
import { CustomFetch } from '#imports'
|
|
108
111
|
|
|
109
112
|
const ajax = new CustomFetch({ baseURL: '/api' })
|
|
110
113
|
|
|
@@ -160,12 +163,22 @@ export function getReactivePageList (page: Ref<number>) {
|
|
|
160
163
|
|
|
161
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.
|
|
162
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
|
+
|
|
163
175
|
## Request Semantics
|
|
164
176
|
|
|
165
177
|
### Key generation and dedupe
|
|
166
178
|
|
|
167
|
-
- Without an explicit `key`, the module hashes `url + method + resolved request options`.
|
|
168
|
-
- 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.
|
|
169
182
|
- `immutableKey: true` makes the generated key depend only on the URL.
|
|
170
183
|
- If you need exact cache control, provide your own `key`.
|
|
171
184
|
- Same key means shared async-data state.
|
|
@@ -181,13 +194,12 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
181
194
|
### Handler behavior
|
|
182
195
|
|
|
183
196
|
- `handler` receives a merged object built from `params` and `query`.
|
|
184
|
-
-
|
|
185
|
-
-
|
|
186
|
-
- 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`.
|
|
187
199
|
|
|
188
200
|
### Client compatibility mode
|
|
189
201
|
|
|
190
|
-
- 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).
|
|
191
203
|
- If no Nuxt-managed keyed state exists yet, the module creates and caches a compatibility async-data instance by key.
|
|
192
204
|
- `refresh`, `execute`, `clear`, `watch`, status updates, and cancellation still work in this mode.
|
|
193
205
|
- This mode should not be treated as a full SSR payload cache replacement.
|
|
@@ -198,7 +210,7 @@ The remaining helper names follow the same rule: `getPageList` is the plain non-
|
|
|
198
210
|
const ajax = new CustomFetch({
|
|
199
211
|
baseURL: '',
|
|
200
212
|
immutableKey: false,
|
|
201
|
-
showLogs:
|
|
213
|
+
showLogs: import.meta.dev,
|
|
202
214
|
useHandler: true,
|
|
203
215
|
handler: undefined,
|
|
204
216
|
onRequest: undefined,
|
|
@@ -215,11 +227,14 @@ Available methods:
|
|
|
215
227
|
- `ajax.post(url, config?, asyncDataOptions?)`
|
|
216
228
|
- `ajax.request(url, { method, ...config }, asyncDataOptions?)`
|
|
217
229
|
|
|
218
|
-
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.
|
|
219
233
|
|
|
220
234
|
## Typing Notes
|
|
221
235
|
|
|
222
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`.
|
|
223
238
|
- Playground examples and type tests cover explicit generics, default values, and reactive arguments.
|
|
224
239
|
- If you want a custom wrapper with only shared defaults, Nuxt's `createUseFetch` and `createUseAsyncData` remain the simpler choice.
|
|
225
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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { NitroFetchRequest } from '
|
|
1
|
+
import type { NitroFetchRequest } from 'nitropack';
|
|
2
2
|
import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
|
|
3
3
|
import type { CustomFetchOptions, CustomFetchRequestOptions, Interceptors, KeysOf, PickFrom } from './type.js';
|
|
4
4
|
import { Noop } from './utils.js';
|
|
@@ -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 {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { serialize } from "ohash";
|
|
2
|
+
import { hashKey } from "#app";
|
|
3
|
+
import { asyncDataDefaults, granularCachedData, pendingWhenIdle } from "#build/nuxt.config.mjs";
|
|
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
|
}
|
|
@@ -15,13 +14,24 @@ function linkAbortSignal(signal, controller) {
|
|
|
15
14
|
return;
|
|
16
15
|
}
|
|
17
16
|
if (signal.aborted) {
|
|
18
|
-
controller.abort();
|
|
17
|
+
controller.abort(signal.reason);
|
|
19
18
|
return;
|
|
20
19
|
}
|
|
21
|
-
signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
20
|
+
signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
|
|
22
21
|
}
|
|
23
|
-
function
|
|
24
|
-
|
|
22
|
+
function createMergedSignal(signals, timeout) {
|
|
23
|
+
const controller = createAbortController();
|
|
24
|
+
if (!controller) {
|
|
25
|
+
return void 0;
|
|
26
|
+
}
|
|
27
|
+
const sources = signals.filter((signal) => !!signal);
|
|
28
|
+
if (typeof timeout === "number" && timeout >= 0 && typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
|
|
29
|
+
sources.push(AbortSignal.timeout(timeout));
|
|
30
|
+
}
|
|
31
|
+
for (const signal of sources) {
|
|
32
|
+
linkAbortSignal(signal, controller);
|
|
33
|
+
}
|
|
34
|
+
return controller.signal;
|
|
25
35
|
}
|
|
26
36
|
function pruneClientAsyncDataCache() {
|
|
27
37
|
while (_cachedClientAsyncData.size > MAX_UNSCOPED_CLIENT_ASYNC_DATA_ENTRIES) {
|
|
@@ -33,6 +43,24 @@ function pruneClientAsyncDataCache() {
|
|
|
33
43
|
asyncData.clear();
|
|
34
44
|
}
|
|
35
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
|
+
}
|
|
36
64
|
export function __resetCustomFetchCaches() {
|
|
37
65
|
for (const controller of _cachedController.values()) {
|
|
38
66
|
controller.abort();
|
|
@@ -75,26 +103,25 @@ export class CustomFetch {
|
|
|
75
103
|
const query = resolveReactiveValue(toValue(config.query)) || {};
|
|
76
104
|
const params = resolveReactiveValue(toValue(config.params)) || {};
|
|
77
105
|
const baseHandler = handler || this._baseHandler;
|
|
78
|
-
const _name = Object.keys(query).length ? "query" : "params";
|
|
79
106
|
const mergeObj = {
|
|
80
107
|
...params,
|
|
81
108
|
...query
|
|
82
109
|
};
|
|
83
110
|
if (useHandler && baseHandler && typeof baseHandler === "function") {
|
|
84
|
-
return {
|
|
111
|
+
return { query: baseHandler(mergeObj) };
|
|
85
112
|
}
|
|
86
|
-
return {
|
|
113
|
+
return { query: { ...mergeObj } };
|
|
87
114
|
}
|
|
88
115
|
resolveFetchConfig(config, timeout) {
|
|
89
|
-
const { handler: _handler, useHandler: _useHandler, ...rawConfig } = config;
|
|
116
|
+
const { handler: _handler, useHandler: _useHandler, params: _params, ...rawConfig } = config;
|
|
90
117
|
const baseConfig = this.baseConfig(config);
|
|
91
118
|
const baseURL = toValue(rawConfig.baseURL);
|
|
92
119
|
const body = resolveReactiveValue(toValue(rawConfig.body));
|
|
93
|
-
const
|
|
120
|
+
const _cache = toValue(rawConfig.cache);
|
|
121
|
+
const cache = typeof _cache === "boolean" ? void 0 : _cache;
|
|
94
122
|
const headers = resolveReactiveValue(toValue(rawConfig.headers));
|
|
95
123
|
const method = toValue(rawConfig.method);
|
|
96
|
-
const
|
|
97
|
-
const query = resolveReactiveValue(toValue(baseConfig.query ?? rawConfig.query));
|
|
124
|
+
const query = resolveReactiveValue(toValue(baseConfig.query));
|
|
98
125
|
return {
|
|
99
126
|
...rawConfig,
|
|
100
127
|
...baseConfig,
|
|
@@ -103,7 +130,6 @@ export class CustomFetch {
|
|
|
103
130
|
cache,
|
|
104
131
|
headers,
|
|
105
132
|
method,
|
|
106
|
-
params,
|
|
107
133
|
query,
|
|
108
134
|
timeout
|
|
109
135
|
};
|
|
@@ -151,7 +177,6 @@ export class CustomFetch {
|
|
|
151
177
|
headers: initialFetchConfig.headers,
|
|
152
178
|
key: toValue(resolvedConfig.key),
|
|
153
179
|
method: initialFetchConfig.method,
|
|
154
|
-
params: initialFetchConfig.params,
|
|
155
180
|
query: initialFetchConfig.query
|
|
156
181
|
}).filter(([, value]) => value !== void 0));
|
|
157
182
|
let bodyLogs;
|
|
@@ -160,7 +185,7 @@ export class CustomFetch {
|
|
|
160
185
|
} catch (error) {
|
|
161
186
|
console.warn("[Custom Fetch] couldn't serialize [Body]:", error);
|
|
162
187
|
}
|
|
163
|
-
console.
|
|
188
|
+
console.info([
|
|
164
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",
|
|
165
190
|
`[Request URL]: ${url}`,
|
|
166
191
|
"",
|
|
@@ -215,15 +240,15 @@ export class CustomFetch {
|
|
|
215
240
|
method: initialFetchConfig.method ?? resolvedConfig.method
|
|
216
241
|
}));
|
|
217
242
|
}
|
|
218
|
-
const
|
|
219
|
-
const key = computed(() => toValue(resolvedConfig.key) ||
|
|
243
|
+
const defaultKey = hashKey(hashValue).slice(0, 10);
|
|
244
|
+
const key = computed(() => toValue(resolvedConfig.key) || defaultKey);
|
|
220
245
|
const executeRequest = (executeOptions = {}) => {
|
|
221
|
-
const
|
|
222
|
-
|
|
246
|
+
const timeout = executeOptions.timeout ?? options.timeout;
|
|
247
|
+
const signal = createMergedSignal([executeOptions.signal], timeout);
|
|
223
248
|
return requestFetch(url, {
|
|
224
249
|
...defaultOptions,
|
|
225
|
-
...getResolvedFetchConfig(
|
|
226
|
-
signal
|
|
250
|
+
...getResolvedFetchConfig(timeout),
|
|
251
|
+
signal
|
|
227
252
|
});
|
|
228
253
|
};
|
|
229
254
|
const _handler = (_nuxtApp, context) => {
|
|
@@ -232,30 +257,66 @@ export class CustomFetch {
|
|
|
232
257
|
timeout: options.timeout
|
|
233
258
|
});
|
|
234
259
|
};
|
|
260
|
+
const nuxtApp = useNuxtApp();
|
|
235
261
|
const createClientAsyncDataFallback = () => {
|
|
236
262
|
const _ref = options.deep ? ref : shallowRef;
|
|
263
|
+
const usePendingRef = pendingWhenIdle;
|
|
237
264
|
const getDefaultValue = () => {
|
|
238
265
|
if (options.default) {
|
|
239
266
|
return unref(options.default());
|
|
240
267
|
}
|
|
241
268
|
return asyncDataDefaults.value;
|
|
242
269
|
};
|
|
270
|
+
const resolveCachedData = (cause = "refresh:manual") => {
|
|
271
|
+
if (options.getCachedData) {
|
|
272
|
+
return options.getCachedData(key.value, nuxtApp, { cause });
|
|
273
|
+
}
|
|
274
|
+
if (nuxtApp.isHydrating) {
|
|
275
|
+
return nuxtApp.payload?.data?.[key.value];
|
|
276
|
+
}
|
|
277
|
+
if (cause !== "refresh:manual" && cause !== "refresh:hook") {
|
|
278
|
+
return nuxtApp.static?.data?.[key.value];
|
|
279
|
+
}
|
|
280
|
+
return void 0;
|
|
281
|
+
};
|
|
282
|
+
const writePayloadData = (value) => {
|
|
283
|
+
if (nuxtApp.payload?.data) {
|
|
284
|
+
nuxtApp.payload.data[key.value] = value;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const isKeyReactive = isRef(resolvedConfig.key) || typeof resolvedConfig.key === "function";
|
|
243
288
|
let activeController;
|
|
244
289
|
let activeRequest;
|
|
245
290
|
let requestId = 0;
|
|
291
|
+
let hasData = false;
|
|
292
|
+
let keyChanging = false;
|
|
246
293
|
let stopKeyWatch;
|
|
247
294
|
let stopOptionWatch;
|
|
295
|
+
let stopEnabledWatch;
|
|
296
|
+
let stopRefreshHook;
|
|
297
|
+
const initialStatus = options.immediate === false || toValue(options.enabled) === false ? "idle" : "pending";
|
|
298
|
+
const statusRef = _ref(initialStatus);
|
|
299
|
+
const pendingRef = usePendingRef ? _ref(initialStatus === "pending") : computed(() => statusRef.value === "pending");
|
|
300
|
+
const setPending = (value) => {
|
|
301
|
+
if (usePendingRef) {
|
|
302
|
+
pendingRef.value = value;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
248
305
|
const stopWatchers = () => {
|
|
249
306
|
stopKeyWatch?.();
|
|
250
307
|
stopKeyWatch = void 0;
|
|
251
308
|
stopOptionWatch?.();
|
|
252
309
|
stopOptionWatch = void 0;
|
|
310
|
+
stopEnabledWatch?.();
|
|
311
|
+
stopEnabledWatch = void 0;
|
|
312
|
+
stopRefreshHook?.();
|
|
313
|
+
stopRefreshHook = void 0;
|
|
253
314
|
};
|
|
254
315
|
const asyncData = {
|
|
255
316
|
data: _ref(getDefaultValue()),
|
|
256
317
|
error: _ref(asyncDataDefaults.errorValue),
|
|
257
|
-
status:
|
|
258
|
-
pending:
|
|
318
|
+
status: statusRef,
|
|
319
|
+
pending: pendingRef,
|
|
259
320
|
clear: () => {
|
|
260
321
|
stopWatchers();
|
|
261
322
|
activeController?.abort();
|
|
@@ -263,16 +324,18 @@ export class CustomFetch {
|
|
|
263
324
|
if (_cachedClientAsyncData.get(key.value) === asyncData) {
|
|
264
325
|
_cachedClientAsyncData.delete(key.value);
|
|
265
326
|
}
|
|
327
|
+
hasData = false;
|
|
266
328
|
asyncData.data.value = getDefaultValue();
|
|
267
329
|
asyncData.error.value = asyncDataDefaults.errorValue;
|
|
268
330
|
asyncData.status.value = "idle";
|
|
269
|
-
|
|
331
|
+
setPending(false);
|
|
270
332
|
clearNuxtData(key.value);
|
|
271
333
|
},
|
|
272
334
|
refresh: async (executeOptions) => {
|
|
273
335
|
await asyncData.execute(executeOptions);
|
|
274
336
|
},
|
|
275
337
|
execute: async (executeOptions) => {
|
|
338
|
+
const cause = executeOptions?.cause;
|
|
276
339
|
const dedupe = executeOptions?.dedupe ?? options.dedupe ?? "cancel";
|
|
277
340
|
if (activeRequest) {
|
|
278
341
|
if (dedupe === "defer") {
|
|
@@ -280,6 +343,21 @@ export class CustomFetch {
|
|
|
280
343
|
}
|
|
281
344
|
activeController?.abort();
|
|
282
345
|
}
|
|
346
|
+
if (granularCachedData || cause === "initial" || nuxtApp.isHydrating) {
|
|
347
|
+
const cachedData = resolveCachedData(cause);
|
|
348
|
+
if (cachedData !== void 0) {
|
|
349
|
+
writePayloadData(cachedData);
|
|
350
|
+
hasData = true;
|
|
351
|
+
asyncData.data.value = cachedData;
|
|
352
|
+
asyncData.error.value = asyncDataDefaults.errorValue;
|
|
353
|
+
asyncData.status.value = "success";
|
|
354
|
+
setPending(false);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (toValue(options.enabled) === false) {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
283
361
|
const currentRequestId = ++requestId;
|
|
284
362
|
const controller = createAbortController();
|
|
285
363
|
activeController = controller;
|
|
@@ -287,7 +365,7 @@ export class CustomFetch {
|
|
|
287
365
|
if (controller) {
|
|
288
366
|
_cachedController.set(key.value, controller);
|
|
289
367
|
}
|
|
290
|
-
|
|
368
|
+
setPending(true);
|
|
291
369
|
asyncData.status.value = "pending";
|
|
292
370
|
asyncData.error.value = asyncDataDefaults.errorValue;
|
|
293
371
|
activeRequest = executeRequest({
|
|
@@ -305,13 +383,17 @@ export class CustomFetch {
|
|
|
305
383
|
if (options.pick) {
|
|
306
384
|
finalData = pick(data, options.pick);
|
|
307
385
|
}
|
|
308
|
-
|
|
386
|
+
const value = finalData;
|
|
387
|
+
writePayloadData(value);
|
|
388
|
+
hasData = true;
|
|
389
|
+
asyncData.data.value = value;
|
|
309
390
|
asyncData.error.value = asyncDataDefaults.errorValue;
|
|
310
391
|
asyncData.status.value = "success";
|
|
311
392
|
}).catch((error) => {
|
|
312
393
|
if (currentRequestId !== requestId || controller?.signal.aborted) {
|
|
313
394
|
return;
|
|
314
395
|
}
|
|
396
|
+
hasData = false;
|
|
315
397
|
asyncData.error.value = createError(error);
|
|
316
398
|
asyncData.data.value = getDefaultValue();
|
|
317
399
|
asyncData.status.value = "error";
|
|
@@ -325,77 +407,103 @@ export class CustomFetch {
|
|
|
325
407
|
if (asyncData.status.value === "pending") {
|
|
326
408
|
asyncData.status.value = "idle";
|
|
327
409
|
}
|
|
328
|
-
|
|
410
|
+
setPending(false);
|
|
329
411
|
});
|
|
330
412
|
await activeRequest;
|
|
331
413
|
}
|
|
332
414
|
};
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
_cachedController.get(oldKey)?.abort?.();
|
|
337
|
-
_cachedController.delete(oldKey);
|
|
338
|
-
if (_cachedClientAsyncData.get(oldKey) === asyncData) {
|
|
339
|
-
_cachedClientAsyncData.delete(oldKey);
|
|
340
|
-
}
|
|
415
|
+
const cancelActiveRequest = (reason) => {
|
|
416
|
+
if (!activeRequest) {
|
|
417
|
+
return;
|
|
341
418
|
}
|
|
342
|
-
|
|
343
|
-
|
|
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";
|
|
344
426
|
}
|
|
345
|
-
|
|
346
|
-
|
|
427
|
+
setPending(false);
|
|
428
|
+
};
|
|
429
|
+
_cachedClientAsyncData.set(key.value, asyncData);
|
|
430
|
+
stopRefreshHook = nuxtApp.hook?.("app:data:refresh", async (keys) => {
|
|
431
|
+
if (!keys || keys.includes(key.value)) {
|
|
432
|
+
await asyncData.execute({ cause: "refresh:hook" });
|
|
347
433
|
}
|
|
348
434
|
});
|
|
435
|
+
if (isKeyReactive) {
|
|
436
|
+
stopKeyWatch = watch(key, (newKey, oldKey) => {
|
|
437
|
+
if (!((newKey || oldKey) && newKey !== oldKey)) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
keyChanging = true;
|
|
441
|
+
const hadData = hasData;
|
|
442
|
+
const wasRunning = activeRequest !== void 0;
|
|
443
|
+
if (oldKey) {
|
|
444
|
+
_cachedController.get(oldKey)?.abort?.();
|
|
445
|
+
_cachedController.delete(oldKey);
|
|
446
|
+
if (_cachedClientAsyncData.get(oldKey) === asyncData) {
|
|
447
|
+
_cachedClientAsyncData.delete(oldKey);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
_cachedClientAsyncData.set(newKey, asyncData);
|
|
451
|
+
const keyTriggersExecute = options._keyTriggersExecute !== false;
|
|
452
|
+
if (keyTriggersExecute && (options.immediate !== false || hadData || wasRunning)) {
|
|
453
|
+
void asyncData.execute({ cause: "watch" });
|
|
454
|
+
}
|
|
455
|
+
void Promise.resolve().then(() => {
|
|
456
|
+
keyChanging = false;
|
|
457
|
+
});
|
|
458
|
+
}, { flush: "sync" });
|
|
459
|
+
}
|
|
349
460
|
const hasScope = getCurrentScope();
|
|
350
461
|
if (options.watch) {
|
|
351
462
|
stopOptionWatch = watch(options.watch, async () => {
|
|
463
|
+
if (keyChanging) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
352
466
|
await asyncData.refresh({ cause: "watch" });
|
|
353
467
|
}, { flush: "post" });
|
|
354
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
|
+
}
|
|
355
476
|
if (!hasScope) {
|
|
356
477
|
pruneClientAsyncDataCache();
|
|
357
478
|
}
|
|
358
479
|
if (hasScope) {
|
|
359
|
-
onScopeDispose(
|
|
480
|
+
onScopeDispose(() => {
|
|
481
|
+
stopWatchers();
|
|
482
|
+
cancelActiveRequest("AsyncData request cancelled by unmount");
|
|
483
|
+
});
|
|
360
484
|
}
|
|
361
485
|
if (options.immediate === false) {
|
|
362
486
|
return Promise.resolve(asyncData);
|
|
363
487
|
}
|
|
364
488
|
return asyncData.execute({ cause: "initial" }).then(() => asyncData);
|
|
365
489
|
};
|
|
366
|
-
const nuxtApp = useNuxtApp();
|
|
367
490
|
const sharedAsyncData = nuxtApp._asyncData?.[key.value];
|
|
368
491
|
const cachedClientAsyncData = _cachedClientAsyncData.get(key.value);
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
dedupe: options.dedupe
|
|
374
|
-
});
|
|
375
|
-
return sharedAsyncData;
|
|
376
|
-
}
|
|
377
|
-
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) {
|
|
378
496
|
if (options.immediate === false) {
|
|
379
|
-
return Promise.resolve(
|
|
497
|
+
return Promise.resolve(reusableAsyncData);
|
|
380
498
|
}
|
|
381
|
-
return
|
|
499
|
+
return reusableAsyncData.execute({
|
|
382
500
|
cause: "initial",
|
|
383
501
|
dedupe: options.dedupe
|
|
384
|
-
}).then(() =>
|
|
385
|
-
}
|
|
386
|
-
return createClientAsyncDataFallback();
|
|
387
|
-
}
|
|
388
|
-
try {
|
|
389
|
-
return useAsyncData(key, _handler, options);
|
|
390
|
-
} catch (error) {
|
|
391
|
-
if (!import.meta.client || !shouldFallbackToClientAsyncData(error)) {
|
|
392
|
-
throw error;
|
|
393
|
-
}
|
|
394
|
-
if (import.meta.dev) {
|
|
395
|
-
console.warn("[Custom Fetch] Falling back to client compatibility mode outside setup-compatible async data context.");
|
|
502
|
+
}).then(() => reusableAsyncData);
|
|
396
503
|
}
|
|
397
504
|
return createClientAsyncDataFallback();
|
|
398
505
|
}
|
|
506
|
+
return useAsyncData(key, _handler, options);
|
|
399
507
|
}
|
|
400
508
|
get(url, config = {}, options) {
|
|
401
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,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nuxt-custom-fetch",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "4.
|
|
5
|
-
"packageManager": "pnpm@
|
|
4
|
+
"version": "4.5.0",
|
|
5
|
+
"packageManager": "pnpm@11.7.0",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -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": {
|
|
@@ -40,30 +40,34 @@
|
|
|
40
40
|
"path": "node_modules/cz-git"
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"nuxt": ">=4.5.0",
|
|
45
|
+
"vue": "^3.5.30"
|
|
46
|
+
},
|
|
43
47
|
"dependencies": {
|
|
44
48
|
"@vue/shared": "^3.5.30",
|
|
45
|
-
"ohash": "^2.0.11"
|
|
46
|
-
"vue": "^3.5.30"
|
|
49
|
+
"ohash": "^2.0.11"
|
|
47
50
|
},
|
|
48
51
|
"devDependencies": {
|
|
49
|
-
"@antfu/eslint-config": "^
|
|
50
|
-
"@commitlint/cli": "^
|
|
51
|
-
"@commitlint/config-conventional": "^
|
|
52
|
-
"@nuxt/kit": "4.
|
|
52
|
+
"@antfu/eslint-config": "^9.0.0",
|
|
53
|
+
"@commitlint/cli": "^21.0.2",
|
|
54
|
+
"@commitlint/config-conventional": "^21.0.2",
|
|
55
|
+
"@nuxt/kit": "4.5.2",
|
|
53
56
|
"@nuxt/module-builder": "^1.0.2",
|
|
54
|
-
"@nuxt/schema": "4.
|
|
57
|
+
"@nuxt/schema": "4.5.2",
|
|
55
58
|
"@types/node": "^25.5.0",
|
|
56
|
-
"@vitest/coverage-v8": "^
|
|
59
|
+
"@vitest/coverage-v8": "^4.1.9",
|
|
57
60
|
"changelogen": "^0.6.2",
|
|
58
61
|
"commitizen": "^4.3.1",
|
|
59
62
|
"cz-git": "^1.12.0",
|
|
60
63
|
"eslint": "^10.0.3",
|
|
61
64
|
"husky": "^9.1.7",
|
|
62
|
-
"nano-staged": "^0.
|
|
63
|
-
"
|
|
64
|
-
"nuxt": "4.
|
|
65
|
-
"typescript": "
|
|
66
|
-
"vitest": "^
|
|
65
|
+
"nano-staged": "^1.0.2",
|
|
66
|
+
"nitropack": "^2.13.1",
|
|
67
|
+
"nuxt": "4.5.2",
|
|
68
|
+
"typescript": "6.0.3",
|
|
69
|
+
"vitest": "^4.1.9",
|
|
70
|
+
"vue": "^3.5.30"
|
|
67
71
|
},
|
|
68
72
|
"husky": {
|
|
69
73
|
"hooks": {
|
|
@@ -71,6 +75,6 @@
|
|
|
71
75
|
}
|
|
72
76
|
},
|
|
73
77
|
"nano-staged": {
|
|
74
|
-
"*": "eslint
|
|
78
|
+
"*": "eslint --fix"
|
|
75
79
|
}
|
|
76
80
|
}
|